munotes®

Ethical Hacking Notes | B.Sc. (Computer Science) Semester 5 | Mumbai University | munotes

Get access to whole semester resourcesSemester Pass

Official Notes munotes.in

Ethical Hacking

B.SC. (COMPUTER SCIENCE) · SEMESTER 5

Strictly as per the University of Mumbai NEP syllabus in force for B.Sc. (Computer Science)

For B.Sc. (Computer Science) students of the University of Mumbai and all its affiliated colleges

Open the book ↓

munotes.in Third Year

Ethical Hacking

Copyright © 2026 munotes.in. All rights reserved.

Written and first published by munotes.in, 2026.

This book is free for individual students to read at munotes.in. No part of it may be reproduced, distributed, stored, translated or used for institutional or classroom purposes in any form without a prior written licence from munotes.in.

Licensing and permissions: contact@munotes.in

The text of statutes and of judgments reproduced in this book is in the public domain under section 52(1)(q) of the Copyright Act 1957. The commentary, arrangement, examples and questions are the original work of munotes.in.

munotes.in is an independent study resource for MU students. It is not affiliated with, endorsed by, or officially connected to the University of Mumbai. Course names and university references describe the students and syllabus the material relates to.

munotes.in

Contents

Module I The law and ethics of authorised testing, security vocabulary, the five-phase lifecycle, CVE and CVSS, reconnaissance and scanning, enumeration, system and password security, hashing and salting, and network sniffing

  1. How This Course Is Examined: the Journal, the 80 Per Cent Rule and the Two-Hour Practical Paper 1
  2. The Law: What Makes Hacking Lawful 5
  3. The Rest of the Law: Source Code, Identity, Protected Systems and Confidentiality 10
  4. Authorisation in Practice: the Letter, the Scope and the Rules of Engagement 16
  5. The Vocabulary: Asset, Threat, Vulnerability, Exploit and Risk 21
  6. The CIA Triad, and Which Property Each Attack Breaks 26
  7. Hacker Classes, Hacktivism and the Types of Hacking 31
  8. Types of Engagement: Black Box, White Box, Grey Box, Internal and External 36
  9. The Five Phases of an Engagement: a Lifecycle Model 41
  10. The Defender's Mirror: a Control for Every Phase 46
  11. The Life of a Vulnerability 51
  12. Responsible Disclosure Against Full Disclosure, and the Vendor's Side 55
  13. CVE and CWE: Naming the Flaw and Naming the Weakness 60
  14. CVSS: the Eight Base Metrics 64
  15. CVSS: Working a Score, and the Temporal and Environmental Metrics 68
  16. Bug Bounty Programmes 73
  17. A Worked Case Study: Heartbleed 77
  18. A Worked Case Study: Log4Shell 82
  19. Footprinting: Passive Against Active Reconnaissance 87
  20. OSINT on People: Names, Roles and the Email Format 92
  21. OSINT on Technology and Infrastructure 96
  22. Search-Engine Reconnaissance and Document Metadata 101
  23. Reducing Your Own Footprint: the Defensive Audit 106
  24. How the Domain Name System Resolves a Name 111
  25. The Record Types, and What Each One Reveals 116
  26. Subdomain Enumeration and Infrastructure Mapping 121
  27. Zone Transfers and DNS Hardening 126
  28. WHOIS, the Registries and IP Allocation 131
  29. The Psychology: the Levers an Attacker Pulls 136
  30. Phishing, Spear Phishing, Whaling, Smishing and Vishing 141
  31. Pretexting, Baiting, Impersonation and Tailgating 146
  32. A Worked Case: Analysing a Real Attack 151
  33. Defences: Awareness, Verification and Multi-Factor 156
  34. Email Authentication: SPF, DKIM and DMARC 161
  35. TCP/IP for the Scanner: Layers, Addresses, Ports and Flags 166
  36. The Three-Way Handshake, and Why Scanning Works 171
  37. Host Discovery: Finding What Is Alive 176
  38. The Scan Types: Connect, SYN, FIN, NULL and XMAS 181
  39. ACK Scanning and UDP Scanning 186
  40. Port States, Service and Version Detection, and OS Fingerprinting 191
  41. Firewall and Filter Detection 196
  42. How the Scan Is Seen: Intrusion Detection and the Defender's View 201
  43. Enumeration and Banner Grabbing 206
  44. SNMP Enumeration 211
  45. NetBIOS and SMB Enumeration 216
  46. LDAP, SMTP and NTP Enumeration 221
  47. Enumeration Countermeasures: What to Close 226
  48. System Hacking and Privilege Escalation 231
  49. Escalation Routes on Linux and Windows, at Concept Level 236
  50. Detecting Persistence: the Auto-Start Audit 242
  51. Covering Tracks, and Why a Defender Protects the Logs 248
  52. Rootkits: How They Hide and How They Are Found 253
  53. Spyware and Keyloggers from the Defensive Side 258
  54. Encoding, Encryption and Hashing: Three Different Things 262
  55. Symmetric and Asymmetric Encryption at Concept Level 266
  56. Hash Functions and the Properties They Must Have 270
  57. Why a Password Is Never Encrypted: Storage and Salting 275
  58. How Passwords Are Attacked, and the Arithmetic of a Keyspace 280
  59. Password Policy, Managers and Multi-Factor Authentication 284
  60. Cryptographic Weaknesses to Know 289
  61. Hubs, Switches, and Passive Sniffing 293
  62. MAC Flooding 298
  63. ARP Poisoning and the Man in the Middle 302
  64. DNS Spoofing 307
  65. Countermeasures: Switch Controls and Encryption in Transit 312

Module II Denial of service and botnets, session and web-server security, the OWASP Top Ten, SQL injection, buffer overflows, wireless security, malware analysis, exploit frameworks, and penetration testing methodology and reporting

  1. Denial of Service: Attacking Availability 317
  2. Volumetric Attacks and Amplification 321
  3. Protocol Attacks: the SYN Flood in Depth 326
  4. Application-Layer Denial of Service 330
  5. Botnets: Architecture and Command and Control 335
  6. DDoS Mitigation: the Layered Defence 339
  7. Sessions and Tokens: Why They Exist 344
  8. How a Session Is Stolen: Prediction, Sniffing and Script 348
  9. Session Fixation and Cookie Manipulation 353
  10. Cookie Security: Secure, HttpOnly and SameSite 358
  11. Cross-Site Request Forgery 362
  12. Session Defences in Full 366
  13. The Web Server Against the Web Application 370
  14. Common Web Server Misconfigurations 374
  15. Directory Traversal 378
  16. Patch Management 382
  17. Hardening and the Security Response Headers 386
  18. The OWASP Top 10: What It Is and How It Changed 390
  19. A01: Broken Access Control 395
  20. Security Misconfiguration and Cryptographic Failures 399
  21. Software Supply Chain Failures 403
  22. Injection: the Category and Its Members 407
  23. Cross-Site Scripting: Stored, Reflected and DOM-Based 411
  24. Cross-Site Scripting Defences: Output Encoding and Content Security Policy 415
  25. Insecure Design and Authentication Failures 420
  26. Integrity, Logging and Exceptional Conditions 424
  27. Server-Side Request Forgery 428
  28. Input Validation: the Thread Through the Whole List 432
  29. SQL Injection: How Input Becomes Logic 437
  30. The Types: In-Band, Union-Based and Error-Based 441
  31. Blind SQL Injection: Boolean and Time-Based 445
  32. Prevention: the Parameterised Query 449
  33. Defence in Depth: Least Privilege, Validation and the Web Application Firewall 454
  34. Memory Layout: the Stack, the Heap and the Frame 459
  35. Stack-Based Buffer Overflow and Return-Address Overwriting 463
  36. Heap Overflows and Format-String Flaws, Briefly 467
  37. Defences: Bounds Checking, Canaries, DEP, ASLR and Safe Languages 471
  38. How Wi-Fi Works: Frames, SSIDs and Association 476
  39. WEP and Why It Broke 480
  40. WPA and WPA2: AES and the Four-Way Handshake 484
  41. WPA3 and the SAE Handshake 488
  42. Wireless Attacks: Deauthentication, Evil Twins and Rogue Access Points 492
  43. Wireless Best Practice and Enterprise Authentication 497
  44. The Malware Families 501
  45. Viruses and Worms 505
  46. Trojans, Ransomware and Remote Access Tools 509
  47. Keyloggers and Spyware: the Architecture 514
  48. Detection: Signature, Heuristic and Behavioural 518
  49. Safe Analysis: the Sandbox 523
  50. Endpoint Protection 527
  51. What an Exploit Framework Is 531
  52. The Exploit Lifecycle and the Payload 535
  53. Post-Exploitation, Bounded by Scope 539
  54. The Ethical and Legal Limits of Penetration-Testing Tools 544
  55. Why Methodology Matters More Than Tricks 549
  56. PTES: the Seven Phases 553
  57. The OWASP Testing Guide 557
  58. Risk Assessment and Rating 561
  59. The Penetration-Test Report 565
  60. A Worked Specimen Report 569
  61. Retesting and Closing the Engagement 574
munotes.in

Module I

The law and ethics of authorised testing, security vocabulary, the five-phase lifecycle, CVE and CVSS, reconnaissance and scanning, enumeration, system and password security, hashing and salting, and network sniffing

munotes.in

Chapter One

How This Course Is Examined: the Journal, the 80 Per Cent Rule and the Two-Hour Practical Paper

Syllabus topic Evaluation Scheme, Section B (Evaluation for Practical Courses), MU item 6.33 (N)

In one line

Ethical Hacking is a practical course worth 50 marks: 20 inside the college and 30 in a final practical examination. To be allowed into that final examination at all you need a certified journal and at least 80 per cent of the practicals done. There is no viva in this scheme.

In the wording that matters for planning your term: the University assesses this paper the way it assesses every two-credit practical course under item 6.33 (N), and the split is fixed. Knowing it now changes how you work all semester, which is why it is the first thing in the book.

Why this chapter exists

Most students find out how a paper is marked a week before it. In a practical subject that is too late, because two of the conditions are things you build up over the whole term and cannot make up at the end: the journal, and the 80 per cent completion. Miss either and you are not permitted to appear, however well you know the material. So we put the rules where you will read them on day one.

There is a second reason this chapter comes first, and it runs through the whole book. This is a course about attacks, and it is examined as a course about defence and understanding: the journal asks for the concept and the defensive reading of each practical, not a trophy of a break-in, and the practical paper asks you to demonstrate and explain, not to cause harm. The examination scheme therefore already tells you the register the University expects, and this book follows it: every attack is taught with its detection and its defence, and every practical is written up defensively. Reading the marking scheme first is reading the University's own statement of what this subject is for.

The marks, exactly as MU prints them

The paper carries 50 marks, divided like this.

PartComponentMarks
Internal (20)Mid-term practical examination15
Internal (20)Final journal5
External (30)Semester-end practical examination, 2 hours30

The external 30 is itself two questions:

QuestionBased onMarks
Q.1Module 115
Q.2Module 215

Two conditions are printed as notes under that table, and both are absolute:

  1. A certified journal is compulsory for appearing at the practical examination.
  2. At least 80 per cent of the practicals must be completed, which for a course of twenty practicals means sixteen.

"Individual passing in internal and external" applies: you must reach 40 per cent in each part on its own, not 40 per cent of the total. Failing one and carrying it on the strength of the other is not allowed.

The practical consequence for planning is that the marks are spread across the whole term, not gathered at the end. Fifteen internal marks are decided at a mid-term practical, before the semester is half over, so a student who intends to start late has already lost the chance to prepare for those. The journal accumulates entry by entry as the practicals are done. Only the final thirty are decided at the end. So the work that earns this paper is spread over the term by design, and treating it as an end-of-term subject forfeits marks that were awarded earlier.

munotes.in1

How This Course Is Examined: the Journal, the 80 Per Cent Rule and the Two-Hour Practical Paper

What "no viva" means for you

The first-year Computer Science Practical (item 6.5 (R)) reserves six marks for an oral examination. This scheme does not. Item 6.33 (N) prints a mid-term practical, a journal and a two-hour final, and no oral component anywhere. This book therefore ends each chapter with a section called "Test yourself" rather than pretending there are viva marks to win.

That the questions are not for viva marks does not make them optional. The same understanding they build is tested in two places that do carry marks: the journal's concept and defensive-point lines, where you must explain in your own words what a practical demonstrates and how the technique is detected and prevented, and the practical examination itself, where the examiner walking the lab will ask you to explain what you are doing. A student who can answer the end-of-chapter questions can write the journal's understanding lines and can explain their work to the examiner, so the questions feed directly into the parts that are marked, even though there is no separate oral.

The journal, and the house form this book uses

The journal is the record of your practicals, and it is worth marks twice: five of its own, and it is your ticket into the final. An examiner certifies it, so it must be complete and it must be yours.

Every practical in this book is written up in the same shape, and you should copy that shape into your journal:

  1. Aim. One line: what the practical demonstrates.
  2. Concept. Two or three sentences in your own words on the idea behind it. This is where the marks for understanding are.
  3. Tools and setup. What you used, and on whose system. For this subject that is always your own machine, or a lab machine you have been given, or a system you have written permission to test, and never anything else. The next chapters explain why that line is the whole subject.
  4. Steps and observations. What you did and what you saw, with the output pasted or described.
  5. The defensive point. For every attack technique, one line on how it is detected and one on how it is prevented. In this subject a write-up that shows only the attack is an incomplete write-up.
  6. Conclusion. What you learned, in a sentence.
munotes.in2

How This Course Is Examined: the Journal, the 80 Per Cent Rule and the Two-Hour Practical Paper

The reason the form is worth following exactly is that it is built to earn the marks the scheme actually awards. The concept line is where the understanding marks live; the tools-and-setup line records the authorisation that makes the practical lawful; and the defensive-point line is what turns an attack write-up into the defensive account this subject expects. A journal of bare steps with no concept and no defensive reading is a weaker journal even when every step is correct, because it omits the two things the subject is marked on.

A worked example of a journal entry

Suppose the practical is "score a published vulnerability with CVSS" (a later chapter). A complete entry reads:

Aim. To turn the characteristics of a published vulnerability into its CVSS v3.1 base score by hand and by program.

Concept. CVSS is a way of turning a vulnerability into a number from 0 to 10 so a team can decide what to fix first. It scores how a flaw can be reached and how much damage it does, not whether anyone has been attacked.

Tools and setup. A calculator and a short program, on my own lab machine; no system belonging to anyone else is touched, because scoring a published vulnerability uses only its public description.

Steps and observations. Wrote the vector describing the vulnerability; computed the sub-scores; obtained the base score; confirmed it with the calculator and against the public vulnerability database, which lists the same score.

The defensive point. A high base score tells a defender to patch this early. It is detected by a vulnerability scanner reading version banners; it is prevented by keeping the software patched.

Conclusion. The score is reproducible, which is the point of a standard.

That is a full entry: an aim, the idea in plain words, the authorised setup, the work, the defensive reading, and a conclusion. Nothing in it is an attack on anyone, which is exactly what the subject asks for.

What beginners get wrong

  • Treating this as an end-of-term subject. Fifteen internal marks are decided at a mid-term practical and the journal accumulates all term, so most of the paper is earned before the end; starting late forfeits marks already awarded.
  • Neglecting the journal until the deadline. It is worth five marks and is the compulsory ticket into the final, and it must be certified as complete and yours; a journal rushed at the end risks both the marks and eligibility.
  • Ignoring the 80 per cent rule. At least sixteen of twenty practicals must be completed to appear at all, and this cannot be made up at the end, so falling behind on practicals can bar you from the examination however well you know the theory.
  • Assuming no viva means no explaining. The concept and defensive-point lines in the journal and the examiner's questions in the lab both test the same understanding for marks, so the end-of-chapter questions matter even though there is no separate oral.
  • Writing attack-only journal entries. A write-up showing only the attack, with no concept and no detection-and-prevention line, is incomplete in this subject, which is marked on understanding and defence.
  • Reading "individual passing" as a total. You must reach the pass mark in the internal and the external separately; a strong internal cannot rescue a failed external or the reverse.
munotes.in3

How This Course Is Examined: the Journal, the 80 Per Cent Rule and the Two-Hour Practical Paper

Quick revision

  • 50 marks: internal 20 (mid-term practical 15, journal 5), external 30 (a two-hour practical, Q.1 Module 1 for 15, Q.2 Module 2 for 15).
  • To appear at all: a certified journal, and at least 16 of 20 practicals done.
  • Individual passing: 40 per cent in each of internal and external, separately.
  • No viva in this scheme; but the journal's concept and defensive-point lines and the examiner's lab questions test the same understanding for marks.
  • Every journal entry: aim, concept, tools and setup (on an authorised system only), steps and observations, the defensive point (detection and prevention), conclusion.

Test yourself

  1. How many marks is the final practical examination, how long is it, and how is it divided between the modules?

Thirty marks, two hours, split 15 for a Module 1 question and 15 for a Module 2 question.

  1. What two conditions must be met before you are allowed to sit that examination?

A certified journal, and at least 80 per cent (sixteen of twenty) of the practicals completed. Both accumulate over the term and cannot be made up at the end.

  1. Does this course carry viva marks, and does that make the end-of-chapter questions unimportant?

No, item 6.33 (N) prints a mid-term practical, a journal and a final practical, with no oral component. The questions remain important because the same understanding they build is what the journal's concept and defensive-point lines and the examiner's lab questions test for marks.

  1. What does "individual passing in internal and external" mean?

You must reach the pass mark in each part separately; a strong internal cannot rescue a failed external or the reverse.

  1. Why does the examination scheme itself tell you the register this subject expects?

Because it marks the concept and the defensive reading of each practical, not a demonstration of a break-in, and the practical paper asks you to demonstrate and explain rather than to cause harm, so the scheme already states that the subject is about defence and understanding, which is why this book teaches every attack with its detection and defence and writes up every practical defensively.

Contents This chapter on its own page

munotes.in4

Chapter Two

The Law: What Makes Hacking Lawful

Syllabus topic Module 1, "Foundations of Ethical Hacking and Cyber Terminology ... legal boundaries"; Course Objective 1, "legal frameworks in ethical hacking"

In one line

What makes hacking "ethical" is not the technique. It is permission. The same command is a professional service on a system you have written authorisation to test, and a criminal offence on a system you do not. There is no third category.

In the wording a student can write in an examination: ethical hacking is the authorised, scoped and lawful assessment of a system's security, performed with the informed permission of the system's owner, to find and help fix weaknesses before a malicious attacker exploits them. Remove the authorisation and every other word stays true while the activity becomes a crime.

Why the law is the first thing, not the last

Every other set of notes on this subject puts the law in a short final chapter that nobody reads. That is the wrong order, and it is dangerous, because the techniques in this book are genuinely usable. A student who learns to scan, enumerate and exploit without ever learning the boundary can do real harm to real people and can go to prison for it, and will have been failed by their notes. So we draw the boundary first, in the University's own words, and then every later chapter can be read safely inside it.

There is a second reason, less obvious and more useful. The law is not an obstacle bolted onto this profession. It is the thing that creates the profession. An organisation lets a stranger attack its systems only because a contract and a statute make the terms clear and the consequences of straying certain. A penetration tester who understands the boundary can offer a service; one who does not is indistinguishable from the threat they were hired to simulate.

The boundary is drawn, in India, by one Act: the Information Technology Act 2000. Two of its sections do almost all the work, and the relationship between them is the single most important thing in this chapter.

The provision: section 43, and the words that define the subject

Section 43 of the IT Act 2000 opens:

If any person without permission of the owner or any other person who is in charge of a computer, computer system or computer network, [does any of the acts (a) to (j)] ... he shall be liable to pay damages by way of compensation to the person so affected.

The acts listed in (a) to (j) are, almost exactly, the syllabus of this book.

ClauseThe actWhere this book teaches it
(a)accesses or secures access to a computer, system, network or resourcethe whole of gaining access
(b)downloads, copies or extracts data or informationenumeration, exfiltration
(c)introduces a computer contaminant or virusmalware
(d)damages data, a database or programmesdestructive payloads
(e)disrupts a computer, system or networkdenial of service
(f)denies access to an authorised persondenial of service
(g)provides assistance to another to facilitate access in contraventionsupplying tools or access
(h)charges services availed to another person's accountfraud by manipulation
(i)destroys, deletes or alters information, or diminishes its valuetampering
(j)steals, conceals, destroys or alters source code with intent to cause damagesource-code theft
munotes.in5

The Law: What Makes Hacking Lawful

Read that table and you have read the practical content of this course. Scanning and access fall under (a). Enumeration and data extraction fall under (b). A denial-of-service test falls under (e) and (f). Malware analysis that escapes its sandbox could reach (c).

So what stands between a penetration tester and liability under section 43? Only the opening words: without permission of the owner. Permission is not a nicety or a professional courtesy. It is the entire legal difference between the profession and the crime.

Three things section 43 does not require, and why each matters

This is where students lose marks, and where careless testers lose their liberty. Section 43 does not require:

  1. Damage. The section is headed "Penalty and compensation for damage", but clause (a) is satisfied by access alone. You need not have broken anything.
  2. Dishonest intent. Curiosity is not a defence. "I only wanted to see if it was possible" describes a state of mind that section 43 does not ask about.
  3. Success in the ordinary sense. Securing access to a computer resource is enough; you need not have reached anything valuable.

Put those together and the rule is stark: touching a system you do not have permission to touch is already a civil wrong, whatever you did next and whatever you meant by it. The three sentences students most often offer, "I only looked", "I was going to report it" and "nothing was damaged", are answers to questions the section never asks.

Section 66: when the civil wrong becomes a crime

Section 43 is civil: you pay compensation to the person affected. Section 66 takes the same list of acts and adds a mental element:

If any person, dishonestly or fraudulently, does any act referred to in section 43, he shall be punishable with imprisonment for a term which may extend to three years or with fine which may extend to five lakh rupees or with both.

The Act does not leave those two words to ordinary meaning. Its Explanation borrows them from the Indian Penal Code: "dishonestly" has the meaning in section 24 IPC (doing something with the intention of causing wrongful gain to one person or wrongful loss to another), and "fraudulently" the meaning in section 25 IPC (doing something with intent to defraud).

munotes.in6

The Law: What Makes Hacking Lawful

So the structure to memorise is a ladder, and the examiner asks you to climb it:

ConductConsequence
Rung 0Access with the owner's permission, within scopeLawful. Neither section applies
Rung 1Access without permission, no dishonest or fraudulent intentSection 43: liable to pay compensation
Rung 2The same acts, done dishonestly or fraudulentlySection 66: up to three years, or up to five lakh rupees, or both

An ethical hacker with written authorisation stands on rung 0. Remove the authorisation and they are on rung 1 the moment they touch the system, and a court may place them on rung 2 depending on what it infers about their purpose.

A worked example

Riya is a final-year student. Her college's result portal is at results.college.test. She notices that changing a number in the address shows another student's marksheet.

Case 1: she has written permission. The college's IT head, who is plainly "in charge" of the system, has given her a signed letter authorising her to test that portal during October. She finds the flaw, writes it up, reports it. Rung 0. Section 43 does not apply, because she is not "without permission of the owner". She is doing exactly what this course trains her to do.

Case 2: she has no permission and reports it anyway. She finds the same flaw uninvited, tells nobody else, and emails the IT head. Her motive is good and the college may well thank her. Rung 1 nonetheless. She accessed a computer resource without permission, and section 43 asks nothing about her motive. Whether the college pursues it is their choice, not her right; the law has already been engaged.

Case 3: she has no permission and downloads the marksheets. She saves two hundred students' results. Now clause (b) is engaged as well as (a), and if a court finds she acted dishonestly or fraudulently, rung 2 and section 66 follows, with imprisonment in view.

Case 4: she tells a friend how to do it. Clause (g), providing assistance to facilitate access in contravention of the Act. Passing on the method is itself an act the section names.

The technique in all four cases is identical: change a number in a URL. Only the paperwork and the purpose differ, and they are the whole of the law.

Distinctions that carry marks

Section 43Section 66
NatureCivilCriminal
Mental element requiredNoneDishonestly or fraudulently
Damage requiredNoNo
ConsequenceCompensation to the person affectedUp to 3 years, or up to 5 lakh rupees, or both
Decided byAdjudicating officer (s.46)Criminal court
Defence of good motiveNot a defenceMay negate the mental element
munotes.in7

The Law: What Makes Hacking Lawful

The most examinable line in the whole chapter: section 66 does not create new conduct. It re-describes section 43's conduct with a guilty mind attached. A student who says "section 66 is about hacking and section 43 is about damage" has it wrong in both halves.

What beginners get wrong

  • "It was insecure, so testing it is fair." The owner's carelessness does not confer permission. Section 43 turns on permission, not on how weak the system was. A door left unlocked is still not an invitation.
  • "I reported it, so I am protected." Reporting is good practice and matters to responsible disclosure, but it is not a defence to unauthorised access. The safe route is to obtain permission first, through a bug bounty or a written scope.
  • "I only scanned, I did not break in." A scan secures access to information about a system and engages clause (a) on its face. Whether a scan alone would be pursued is a separate, practical question; a professional never relies on the argument, because they never need to.
  • "The company is abroad, so Indian law does not apply." Section 75 gives the Act extra-territorial reach where a computer located in India is involved, and the target's own country's law applies as well. Crossing a border multiplies your exposure; it does not remove it.
  • "My college project counts as authorisation." It does not, unless the system's owner has said so in writing. An assignment authorises you to learn, not to test somebody else's systems.

Limits, and what the section is criticised for

Two honest observations a good answer can carry.

First, section 43 is very wide. Clause (a) plus "without permission" catches conduct most people would not think criminal, including a security researcher acting in good faith. India has no general "safe harbour" for good-faith research written into the Act, which is why bug bounty programmes (a later chapter) matter so much: they supply, by contract, the permission the statute demands.

Second, the line between clauses is blurred by modern systems. Accessing a cloud service touches computers in several jurisdictions, and "the owner" of a system may be a chain of providers. The professional answer is not to reason about it afterwards but to name the systems in the scope document beforehand.

Quick revision

  • Ethical hacking = authorised + scoped + lawful. Remove authorisation and only the legality changes; the technique is the same.
  • Section 43: doing any of acts (a) to (j) "without permission of the owner" is a civil wrong; compensation follows. No damage and no dishonest intent are required.
  • Acts (a) to (j) cover access, copying data, contaminants, damage, disruption, denial of access, assisting another, charging to another's account, destroying or altering information, and source-code theft.
  • Section 66: the same acts done "dishonestly or fraudulently" are criminal: up to three years, or up to five lakh rupees, or both. The words take their meaning from ss.24 and 25 IPC.
  • The ladder: permission (lawful), then no permission (s.43, civil), then no permission plus dishonesty (s.66, criminal).
  • Good motive, absence of damage and "I only looked" are answers to questions section 43 does not ask.
munotes.in8

The Law: What Makes Hacking Lawful

Test yourself

  1. What single thing separates ethical hacking from an offence under the IT Act?

Permission of the owner, in writing and within a defined scope. The techniques are identical on either side of the line; only the authorisation differs.

  1. State the relationship between section 43 and section 66.

Section 43 makes a list of acts done "without permission of the owner" a civil wrong attracting compensation, with no need to prove damage or intent. Section 66 takes the same acts and makes them a criminal offence when done dishonestly or fraudulently, punishable with up to three years' imprisonment or up to five lakh rupees or both. Section 66 adds a mental element to section 43's conduct; it does not describe different conduct.

  1. A researcher finds a flaw in a stranger's website, takes nothing, damages nothing, and emails the owner. Has any provision been engaged?

Yes. Section 43 is engaged by securing access without permission; it does not require damage or dishonest intent, so neither the absence of harm nor the good motive prevents liability. Section 66 would require dishonesty or fraud, which is absent here.

  1. Which clauses of section 43 does a denial-of-service test engage, and why is such testing usually forbidden in an engagement?

Clauses (e) (disrupting a computer, system or network) and (f) (denying access to an authorised person). It is usually forbidden because a genuine disruption causes real harm to real users even when well intentioned, so rules of engagement exclude it.

  1. Why is "the system was insecure" not a defence?

Because section 43 turns on the absence of permission, not on the security posture of the target. The owner's failure to secure a system does not amount to permission to access it.

Contents This chapter on its own page

munotes.in9

Chapter Three

The Rest of the Law: Source Code, Identity, Protected Systems and Confidentiality

Syllabus topic Module 1, "Foundations of Ethical Hacking and Cyber Terminology ... legal boundaries"; Course Objective 1, "legal frameworks in ethical hacking"

In one line

Beyond sections 43 and 66, the Act punishes tampering with source code, stealing an identity, pretending to be someone by computer, touching a system the Government has declared protected, and leaking what you saw. Each maps to something this book teaches you to do, and therefore to something you must not do without authorisation.

In examination wording: the Information Technology Act 2000 supplements its core provisions with offences addressing source-code tampering (s.65), receipt of stolen computer resources (s.66B), identity theft (s.66C), cheating by personation using a computer resource (s.66D), cyber terrorism (s.66F), unauthorised access to protected systems (s.70) and breach of confidentiality (s.72), and it applies extra-territorially under s.75 where a computer located in India is involved.

Why a tester needs more than two sections

Sections 43 and 66 answer "may I touch this system?". They do not answer the questions that arise once an engagement is under way, and those questions are where a careless tester strays:

  • I captured a password during the test. May I use it? (s.66C)
  • I want to send a phishing email that appears to come from the client's HR department. (s.66D)
  • The scope names a server that turns out to be part of the national power grid's infrastructure. (s.70)
  • My report contains customer names I saw in a database. (s.72)
  • The client is in Mumbai but the server is in Singapore. (s.75)

Each has a provision behind it, and knowing which is what separates a professional from an enthusiast.

Section 65: tampering with computer source code

Whoever knowingly or intentionally conceals, destroys or alters or intentionally or knowingly causes another to conceal, destroy, or alter any computer source code used for a computer, computer programme, computer system or computer network, when the computer source code is required to be kept or maintained by law for the time being in force, shall be punishable with imprisonment up to three years, or with fine which may extend up to two lakh rupees, or with both.

Two features matter. First, the Act defines "computer source code" broadly in its own Explanation: the listing of programmes, computer commands, design and layout and programme analysis of a computer resource in any form. It is not only the text of a program. Second, and this is the limit students miss, the section bites where the source code is required to be kept or maintained by law. It is aimed at the destruction of records a person was legally obliged to preserve, not at every edit of every file.

For a tester the relevance is direct: an engagement that involves reviewing a client's source code carries an obligation not to alter it, and any modification made during a test is logged and reversed.

munotes.in10

The Rest of the Law: Source Code, Identity, Protected Systems and Confidentiality

Sections 66B, 66C and 66D: stolen resources, identity and personation

These three are the ones a penetration test can blunder into within an hour of starting.

Section 66B, dishonestly receiving a stolen computer resource. Dishonestly receiving or retaining any stolen computer resource or communication device, knowing or having reason to believe it is stolen: up to three years, or up to one lakh rupees, or both. A tester who is handed a dump of credentials from an unexplained source is in this territory, which is why data used in an engagement comes from the client or from the tester's own lawful collection, never from a breach dump of unknown provenance.

Section 66C, identity theft. Fraudulently or dishonestly making use of the electronic signature, password or any other unique identification feature of any other person: up to three years and a fine up to one lakh rupees. This is the section that governs what you do with a credential you recover during a test. Cracking a password hash in a laboratory you own is one thing; using a real employee's recovered password to log in as them is use of another person's unique identification feature, and it is lawful only because, and only to the extent that, the scope authorises it. A scope that says "you may test the login mechanism" does not automatically say "you may log in as a named human being and read their mail".

Section 66D, cheating by personation using a computer resource. Cheating by personation by means of any communication device or computer resource: up to three years and a fine up to one lakh rupees. This is the phishing section. A social-engineering exercise in which you send a message appearing to come from the client's IT department, to induce staff to do something, is personation by computer resource. Performed inside an authorised social-engineering engagement it is a service; performed on your own initiative it is an offence, and the difference is, once again, the scope.

Section 66F: cyber terrorism

Cyber terrorism is defined by intent and effect: acts done with intent to threaten the unity, integrity, security or sovereignty of India, or to strike terror, by denying access to a computer resource, attempting unauthorised access, or introducing a contaminant, and causing or likely to cause death, injuries, damage to property, or disruption of supplies or services essential to the life of the community, or affecting critical information infrastructure. It is punishable with imprisonment which may extend to imprisonment for life.

No ordinary penetration test approaches this, and the section is included for one reason: it marks how seriously the law treats attacks on infrastructure that people depend on. It is the backdrop to section 70.

munotes.in11

The Rest of the Law: Source Code, Identity, Protected Systems and Confidentiality

Section 70: protected systems, and the ten-year line

(1) The appropriate Government may, by notification in the Official Gazette, declare any computer resource which directly or indirectly affects the facility of Critical Information Infrastructure, to be a protected system.

(3) Any person who secures access or attempts to secure access to a protected system in contravention of the provisions of this section shall be punished with imprisonment of either description for a term which may extend to ten years and shall also be liable to fine.

The Act's own Explanation defines Critical Information Infrastructure as a computer resource whose incapacitation or destruction would have a debilitating impact on national security, economy, public health or safety. Power, banking, telecommunications and transport sit here.

Three things follow for a tester, and they are the practical heart of this chapter:

  1. The penalty is ten years, not three. This is the most severe ordinary provision you can stumble into.
  2. An attempt is enough. Section 70(3) punishes securing access or attempting to secure access. A scan that fails still attempted.
  3. You may not know a system is protected by looking at it. A declaration is made by notification in the Gazette, not by a banner on the login page.

That third point is why scope documents name systems explicitly and exclude everything else, and why a tester who discovers an unexpected system during an engagement stops and asks rather than probing. Authorisation to access a protected system comes from the Government's own written authorisation under s.70(2), not from the system's operator alone.

Section 72: confidentiality, and what goes in your report

Section 72 penalises a person who, having secured access to any electronic record, book, register, correspondence, information, document or other material in pursuance of powers conferred under the Act, discloses it to another person without the consent of the person concerned. (The original two-year term was revised to a monetary penalty by later amendment.)

Its neighbour, section 72A, is the one closer to a tester's life: disclosure of personal information obtained while providing services under a lawful contract, without consent and with intent to cause or knowledge of likely wrongful loss or gain, attracts a substantial penalty.

A penetration tester provides services under a lawful contract and routinely sees personal data. The professional discipline that follows is concrete:

  • Do not copy out more data than is needed to prove a finding.
  • Redact personal data in the report; prove the flaw with one masked record, not a spreadsheet of customers.
  • Store test artefacts encrypted, and destroy them at the engagement's end.
  • Never reuse client data in another engagement, a talk or a portfolio.
munotes.in12

The Rest of the Law: Source Code, Identity, Protected Systems and Confidentiality

Section 66A: dead law, still cited

Section 66A once punished sending "grossly offensive" or "menacing" messages by computer. The Supreme Court struck it down in Shreya Singhal v. Union of India (2015) as an unconstitutional restriction on the freedom of speech guaranteed by Article 19(1)(a), being vague and overbroad. The bare Act still prints the text marked Omitted.

Know it for two reasons: examiners ask, and it is still wrongly cited in news reports and even in police practice. A student who can say "66A was struck down in Shreya Singhal and is not law" is demonstrating exactly the currency this subject demands.

Section 75: the Act reaches outside India

Section 75 provides that the Act applies to an offence or contravention committed outside India by any person, if the act involves a computer, computer system or computer network located in India. So a tester in Mumbai who touches a server in Singapore is exposed to Singapore's law, and an attacker abroad who touches a server in India is within reach of this Act. Cross-border work multiplies the legal analysis; it never removes it.

A worked example

Vikram is engaged to test a bank's customer portal. His scope names two web servers and authorises credential testing but says nothing about social engineering or internal systems.

  • He recovers a test account's password from a weak hash and uses it to log in to the named portal. Lawful: the scope authorises testing the login mechanism, and the account is a test account provided by the client. Had it been a real customer's credential, s.66C would demand explicit authorisation he does not have.
  • He decides to email bank staff a message appearing to be from the IT helpdesk, to see who responds. Not lawful: that is personation by computer resource under s.66D, and social engineering is not in his scope.
  • During the test he notices a server belonging to a payment network and probes it. Serious risk: it is outside the scope, so s.43 applies at once, and if it has been notified as a protected system, s.70 applies with its ten-year maximum, and an attempt suffices.
  • His report quotes fifty customers' names and account numbers to prove a data-exposure flaw. Wrong practice and a s.72A risk: one masked record proves the flaw; the rest is unnecessary disclosure of personal information obtained under a services contract.

Every error is a scope error. That is the lesson the next chapter builds on.

Distinctions that carry marks

ProvisionConductMaximum
s.65Concealing, destroying or altering source code required to be kept by law3 years, or 2 lakh, or both
s.66BDishonestly receiving a stolen computer resource3 years, or 1 lakh, or both
s.66CFraudulently using another's signature, password or unique ID feature3 years and 1 lakh
s.66DCheating by personation using a computer resource3 years and 1 lakh
s.70Securing, or attempting to secure, access to a protected system10 years and fine
s.66FCyber terrorismUp to imprisonment for life
munotes.in13

The Rest of the Law: Source Code, Identity, Protected Systems and Confidentiality

What beginners get wrong

  • Treating a recovered password as free to use. Recovering it and using it are different acts; using a real person's credential engages s.66C and needs explicit authorisation.
  • Thinking phishing is only unethical, not illegal. It is personation by computer resource under s.66D. Authorised social-engineering testing is a contracted service; unauthorised phishing is an offence.
  • Assuming a protected system announces itself. Declaration is by Gazette notification. You find out from the scope and the client, not from the server.
  • Citing section 66A. It has been struck down since 2015 and is not law.
  • Putting raw personal data in the report to be thorough. It is the opposite of thorough; it creates a fresh disclosure risk under s.72A. Prove the finding with a masked sample.

Quick revision

  • s.65 source-code tampering (where the code must be kept by law); s.66B receiving a stolen computer resource; s.66C identity theft (using another's password or unique identifier); s.66D cheating by personation (the phishing section); s.66F cyber terrorism (up to life).
  • s.70 protected systems: ten years, and an ATTEMPT is enough. Protected status comes from a Gazette notification, so the scope is how you know.
  • s.72 and s.72A: confidentiality. A tester sees personal data; redact it, minimise it, encrypt it, destroy it.
  • s.66A is Omitted, struck down in Shreya Singhal v. Union of India (2015). Do not cite it as live law.
  • s.75: the Act reaches acts committed outside India involving a computer located in India.

Test yourself

  1. Why does section 70 matter more to a tester than its wording suggests?

Because it carries a ten-year maximum, it punishes an attempt to secure access as well as success, and protected status is conferred by Gazette notification rather than being visible on the system, so a tester can only know from the scope and the client.

  1. A tester recovers a real employee's password during an engagement. Which section governs what they do next, and what makes the use lawful?

Section 66C, identity theft, which covers fraudulently or dishonestly using another person's password or unique identification feature. Use is lawful only to the extent the client's written scope expressly authorises it.

  1. Under which section does a phishing simulation fall, and when is it lawful?

Section 66D, cheating by personation using a computer resource. It is lawful only when the engagement's scope and rules of engagement expressly authorise social-engineering testing.

munotes.in14

The Rest of the Law: Source Code, Identity, Protected Systems and Confidentiality

  1. What is the status of section 66A, and why must you know it?

It was struck down by the Supreme Court in Shreya Singhal v. Union of India (2015) as violating Article 19(1)(a), and the Act prints it as Omitted. It must be known because it is still wrongly cited.

  1. What obligations does section 72A place on how you write a penetration-test report?

It penalises disclosing personal information obtained while providing services under a lawful contract, without consent. So a report minimises and redacts personal data, proves findings with masked samples, stores artefacts securely and destroys them at the engagement's close.

Contents This chapter on its own page

munotes.in15

Chapter Four

Authorisation in Practice: the Letter, the Scope and the Rules of Engagement

Syllabus topic Module 1, "Foundations of Ethical Hacking and Cyber Terminology ... legal boundaries"; Course Objective 1, "legal frameworks in ethical hacking"

In one line

Permission is three documents: an authorisation letter saying who may test what and when, a scope saying exactly which systems are in and which are out, and rules of engagement saying how. If any of the three is missing or vague, the correct professional answer to "can you start?" is no.

In examination wording: lawful authorisation for a security assessment comprises a signed authorisation from a person competent to grant it, a precisely defined scope listing included and excluded targets, and agreed rules of engagement governing timing, permitted and prohibited techniques, data handling and escalation; together these convert conduct that would otherwise fall under section 43 of the IT Act into a contracted professional service.

Why a verbal "go ahead" is not enough

A manager saying "sure, have a look at our website" feels like permission, and it protects nobody. Consider what happens when something goes wrong, which it eventually does:

  • The test causes an outage. The manager now remembers authorising "a look", not a test.
  • The tester reaches a system the manager did not realise was connected, owned by a different department.
  • A third party's system is touched, and that third party never agreed to anything.
  • The manager leaves the company, and the new one asks who this stranger attacking their network is.

In every one of those, the tester's only protection is a document that names what was permitted and who permitted it. Section 43 asks whether you had permission of the owner or any other person who is in charge; a document is how you prove it, and a precise document is how you prove the extent of it.

Document 1: the authorisation letter

Sometimes called the "get out of jail free" letter, which is a joke with a serious core: it is the piece of paper a tester can produce if questioned. A sound one names six things.

  1. Who is authorised. The individual testers by name, and the company they work for.
  2. What they may test. A reference to the scope document, which is separate because it changes.
  3. When. Start and end dates, and permitted hours if restricted.
  4. Who is granting it, and their authority to do so. A name, a role, and ideally a line confirming the signatory is authorised to grant access to the systems concerned.
  5. A statement of permission in words that track the statute: that the named persons are permitted to access the named systems for the purpose of security testing.
  6. A contact reachable during the test.

A teaching specimen:

AUTHORISATION FOR SECURITY TESTING

Metro Retail Private Limited ("the Company") authorises A. Sharma and R. Iyer of Redline Security Private Limited ("the Testers") to perform security testing of the computer systems listed in the Scope Document dated 3 October 2026 (Annexure A), which forms part of this authorisation.

The Testers are permitted to access, scan and test those systems for the purpose of identifying security weaknesses, between 00:01 on 12 October 2026 and 23:59 on 19 October 2026, subject to the Rules of Engagement at Annexure B.

The Company confirms that it owns or controls the systems listed at Annexure A and is competent to grant this authorisation.

Emergency contact during testing: S. Nair, Head of IT, +91 xxxxx xxxxx, available 24 hours.

Signed: S. Nair, Head of Information Technology, for and on behalf of Metro Retail Private Limited. Date: 3 October 2026.

munotes.in16

Authorisation in Practice: the Letter, the Scope and the Rules of Engagement

Note what the specimen does not do: it does not describe techniques (that is the rules of engagement) and it does not list systems (that is the scope). Keeping them separate means the scope can be amended mid-engagement without re-signing the authorisation.

Document 2: the scope

The scope is the most important document of the three, because it is the one that maps directly onto section 43's "without permission". Anything not in scope is a system for which you have no permission.

A scope states, for each target: what it is, how it is identified (domain name, IP address, address range, application name), and any limit on depth. It states exclusions just as explicitly. A teaching specimen:

SCOPE (Annexure A), 3 October 2026

In scope

| Target | Identifier | Depth permitted |

| --- | --- | --- |

| Customer web portal | shop.metro-retail.test | Full testing including authenticated testing with supplied test accounts |

| Portal API | api.metro-retail.test | Full testing |

| Corporate website | www.metro-retail.test | Scanning and unauthenticated testing only |

| External address range | 203.0.113.0/28 | Port scanning and service identification only |

Explicitly out of scope

- Any host not listed above, including any subdomain discovered during testing.

- The payment gateway (operated by a third party) and any host under pay.partner.test.

- Staff, contractors and their personal devices: no social engineering of any kind.

- The corporate wireless network and all internal systems.

- Production customer data: testing uses the supplied test accounts only.

Discovery rule: if a system is found that appears to belong to the Company but is not listed, the Testers will report it and await written confirmation before testing it.

That last rule is the one that saves careers. Reconnaissance routinely turns up a forgotten subdomain, and the instinct is to test it because it obviously belongs to the client. The scope says it does not, until someone writes that it does.

The third-party exclusion matters for the same reason: the client cannot grant permission over a system it does not own. A payment gateway belongs to the gateway, and only the gateway can authorise testing of it.

munotes.in17

Authorisation in Practice: the Letter, the Scope and the Rules of Engagement

Document 3: the rules of engagement

The scope says what; the rules of engagement say how, and they exist mainly to prevent the tester from causing harm while doing their job.

RULES OF ENGAGEMENT (Annexure B)

1. Timing. Testing that may degrade performance is permitted only between 00:01 and 05:00 IST. Passive and low-impact testing may occur at any time.

2. Prohibited techniques. No denial-of-service or stress testing. No social engineering. No physical intrusion. No modification or deletion of production data. No use of real customers' credentials.

3. Exploitation. Exploitation is permitted to the minimum depth needed to demonstrate a finding. Proof of access is to be captured and the access relinquished; no persistence mechanism is to be installed.

4. Data handling. Evidence containing personal data is masked before it leaves the Testers' systems, is stored encrypted, and is destroyed within 30 days of the final report.

5. Stop conditions. Testing stops immediately, and the emergency contact is called, if: a system becomes unresponsive; evidence of a prior, real compromise is found; or personal data is encountered beyond what a finding requires.

6. Deconfliction. The Testers will supply their source addresses in advance so the Company can distinguish testing from a real attack, and will log the start and stop time of each test.

7. Reporting. Critical findings are reported within 24 hours of discovery rather than held for the final report.

Rule 5 is worth pausing on. Finding evidence of a real, prior intrusion is the scenario for which a stop condition exists. You are now standing in a potential crime scene; continuing may destroy evidence and may implicate you. You stop and you telephone.

Rule 6, deconfliction, is what stops the client's security team spending a night responding to you as though you were an attacker, and it is also how the client can later separate your activity from anyone else's in the logs.

A worked example: reading a bad authorisation

A student is offered "freelance security testing" by a small company. The email says:

"Hi, we heard you know about hacking. Please check if our site is secure and let us know. Thanks."

Assess it against the three documents:

  • Authorisation letter? No. An informal email from an unnamed person, with no statement of who they are or whether they can grant access.
  • Scope? No. "Our site" is not an identifier, and nothing says which hosts, whether the API is included, or what is excluded.
  • Rules of engagement? No. Nothing about timing, prohibited techniques, data handling or whom to call.
munotes.in18

Authorisation in Practice: the Letter, the Scope and the Rules of Engagement

The professional response is not to refuse the work but to supply the missing documents: reply asking for a signed authorisation from someone who can grant it, a list of hosts with exclusions, and agreement on techniques and timing. If the company will not provide them, the answer is no, and the reason is that without them the tester is relying on an email that proves nothing about permission under section 43.

A student who can do this, turn a vague request into a scoped engagement, has learned the most commercially useful thing in this chapter.

What beginners get wrong

  • Treating the contract as paperwork to get past. The scope is the legal boundary of everything you are about to do; it is the technical document, not an administrative one.
  • Accepting authorisation from someone without authority. A departmental manager may not be competent to authorise testing of a shared corporate system. The letter should state the signatory's authority.
  • Assuming a discovered subdomain is in scope. It is not, until someone writes that it is. This is the commonest way a good engagement goes wrong.
  • Assuming the client can authorise a third party's systems. They cannot. Cloud providers and payment gateways have their own testing policies that must be checked separately.
  • Forgetting to agree stop conditions. Without them, a tester meeting a live intrusion, or a crashing server, has to improvise at the worst moment.
  • Not supplying source addresses. The client's team wastes a night on an incident that was you.

Quick revision

  • Three documents: authorisation letter (who, what, when, who granted it and on what authority, contact), scope (targets by identifier, depth, and explicit exclusions), rules of engagement (timing, prohibited techniques, exploitation depth, data handling, stop conditions, deconfliction, reporting).
  • Keep them separate so the scope can change without re-signing the authorisation.
  • Anything not named in the scope is out of scope, including subdomains discovered during the test; a discovery rule requires written confirmation before testing them.
  • A client cannot authorise testing of a third party's systems.
  • Stop conditions: unresponsive system, evidence of a real prior compromise, unexpected personal data. Stop and telephone.
  • Deconfliction (supplying source addresses and times) protects the client's team and separates your traffic from a real attacker's.

Test yourself

  1. Name the three documents that constitute authorisation, and say what each governs.

The authorisation letter (who may test, what, when, granted by whom and on what authority), the scope (exactly which systems are in and out, and to what depth), and the rules of engagement (how: timing, permitted and prohibited techniques, exploitation depth, data handling, stop conditions, reporting).

  1. During reconnaissance you discover a subdomain that clearly belongs to the client but is not in the scope. What do you do, and why?
munotes.in19

Authorisation in Practice: the Letter, the Scope and the Rules of Engagement

Report it and await written confirmation before testing it. It is out of scope, so testing it would be access without permission under section 43; ownership by the client is not the same as authorisation to test.

  1. Why must a scope state exclusions explicitly when it already lists what is included?

Because exclusions remove ambiguity in the cases that actually arise: third-party systems the client cannot authorise, staff (social engineering), production data, and anything discovered mid-test. They also record the client's own risk decisions.

  1. Give three stop conditions and explain the reason for one of them.

A system becoming unresponsive; discovering evidence of a real prior compromise; encountering personal data beyond what a finding requires. Discovering a prior compromise means you are in a potential crime scene: continuing risks destroying evidence and implicating you, so you stop and call the emergency contact.

  1. A client emails "please check if our site is secure". Is that authorisation, and what should you do?

No. It identifies no systems, no signatory with stated authority, no timing and no rules. The professional response is to supply the missing documents: request a signed authorisation, a host list with exclusions, and agreed rules of engagement, and to decline if they are not provided.

Contents This chapter on its own page

munotes.in20

Chapter Five

The Vocabulary: Asset, Threat, Vulnerability, Exploit and Risk

Syllabus topic Module 1, "Foundations of Ethical Hacking and Cyber Terminology: Study core terminology"

In one line

An asset is what you are protecting. A vulnerability is a weakness in it. A threat is somebody or something that might harm it. An exploit is the means of turning the weakness into actual harm. Risk is how much you should care.

In examination wording: information security protects assets; a vulnerability is a weakness in a system, process or control that could be exploited; a threat is a potential cause of an unwanted incident; a threat actor is a specific entity that may realise a threat; an exploit is a technique or piece of code that takes advantage of a vulnerability; and risk is the combination of the likelihood of a threat exploiting a vulnerability and the impact if it does.

Why precision here is worth marks and worth money

Security is a field where ordinary words are used loosely by outsiders and precisely by professionals, and the looseness causes real mistakes. "We have a threat" and "we have a vulnerability" call for completely different responses: one is about someone out there, the other about something in here. You cannot remove threats; you can remove vulnerabilities. A team that confuses the two spends its budget in the wrong place.

An examiner marks on whether you use the words as the field uses them, and a client judges a report the same way. So learn them once, exactly, and learn the relationships between them, because the relationships are what the questions actually test.

The terms, built through one example

Picture a small shop that keeps its takings in a back room.

Asset. What you are protecting and why it has value. For the shop, the cash; in our field, information and the systems that hold and move it. Assets are not only data: a reputation is an asset, and so is the availability of a service. A security programme starts by listing assets, because everything else is relative to them. You cannot say a weakness is serious without saying serious to what.

Vulnerability. A weakness that could be taken advantage of. The back room's window has a broken latch. It is a fact about the shop, true whether or not anybody ever notices it, and it stays true while nobody is trying to get in. In software a vulnerability is usually an ordinary mistake: a missing check, a wrong default, a forgotten permission. Every vulnerability was once a bug somebody wrote without noticing.

Threat. A potential cause of an unwanted incident. Burglars exist. A flood is possible. Note carefully: the threat exists independently of your window. You cannot abolish burglars; you can fix the latch.

Threat actor (or adversary). A specific entity that might realise a threat: this burglar, this criminal group, this insider, this state intelligence service. Threat actors differ in motivation (money, ideology, grievance, espionage, mischief), capability (skill, tools, budget) and persistence (whether they give up when it gets hard). A security decision that ignores which actors actually care about you is guesswork.

munotes.in21

The Vocabulary: Asset, Threat, Vulnerability, Exploit and Risk

Attack surface. The sum of all the points where an attacker could try to get in: every window and door, every open port, every input field, every employee with an email address. Reducing the attack surface (closing unused ports, removing unused features) is one of the cheapest defensive moves there is, because it removes possibilities rather than defending them.

Exploit. The means of turning a vulnerability into entry: climbing through the unlatched window, or the crowbar that forces a locked one. In software an exploit is often a small program or a crafted input. The key relationship: an exploit is specific to a vulnerability. There is no general-purpose exploit, which is why attackers must first find out exactly what you are running.

Payload. What the attacker does once inside, as opposed to how they got in. The burglar's payload is taking the cash; a different burglar might photograph documents instead. In software, the same exploit can deliver different payloads, which is why the severity of an intrusion is not determined by the way in alone.

Attack. A threat actor using an exploit against a vulnerability to harm an asset. Attack is the event; the other words are the ingredients.

Zero-day. A vulnerability the defenders do not yet know about, so no fix exists: they have had "zero days" to address it. The word describes knowledge, not severity. A known, patched flaw can be devastating and is not a zero-day; an unknown trivial flaw is one.

Risk. How much you should care, combining how likely the attack is to succeed with how bad it would be. The shop's risk is high if the takings are large, the window is weak, and burglars are active in the area. Change any one of the three and the risk changes.

Mitigation and control. What you do about risk: fix the latch (remove the vulnerability), bank the takings daily (reduce the impact), install an alarm (detect the attack). A control is any measure that reduces risk.

The relationship, in one sentence and one formula

The sentence to memorise: a threat actor uses an exploit against a vulnerability to compromise an asset, and how much you should care is the risk.

The relationship stated as a rough formula, which examiners like:

Risk = Threat x Vulnerability x Impact

Read it as a set of switches rather than real arithmetic. If any factor is effectively zero, the risk is small:

munotes.in22

The Vocabulary: Asset, Threat, Vulnerability, Exploit and Risk

  • A serious vulnerability with no threat actor who cares is low risk. A flaw in software nobody runs harms nobody.
  • A determined threat actor facing no vulnerability is low risk. They are trying, and there is nothing to use.
  • A likely attack on an asset of no value is low risk. Somebody may deface a page nobody reads.

This is why "we have a critical vulnerability" is not by itself an emergency, and why "we are being targeted" is not by itself a disaster. The examinable point is that risk is never a property of the vulnerability alone.

The distinction that costs the most marks

VulnerabilityThreat
Where it isInside your systemOutside, in the world
Whose it isYoursNobody's; it simply exists
Can you remove it?Yes, by fixing itNo, only prepare for it
ExampleAn unpatched web serverCriminal groups that exploit web servers
Discovered byAssessment, scanning, code reviewThreat intelligence, understanding your adversaries

A test you can apply to any sentence: if it describes something you could fix with a change to your own systems, it is a vulnerability. If it describes somebody or something that might come at you, it is a threat. "Our staff click on links" is a vulnerability (train them, add controls). "Criminals send phishing emails" is a threat (they will keep doing it).

A worked example

An online shop runs a web application. Its checkout page trusts a price value sent by the browser.

  • The asset is the shop's revenue and the integrity of its orders.
  • The vulnerability is trusting a price supplied by the client rather than looking it up on the server.
  • The attack surface includes every input the checkout accepts, of which the price field is one.
  • The threat is that people who buy online will try to pay less; the threat actors range from an opportunistic customer to organised fraud.
  • The exploit is editing the hidden price field before submitting.
  • The payload, in the sense of what the attacker gains, is goods at a price they chose.
  • The risk is high: the vulnerability is easy to exploit, the threat actors are numerous and motivated, and the impact scales with every order placed.
  • The mitigation is to look the price up on the server and ignore anything the browser says about it, plus alerting on orders below cost as a detective control.

Notice that naming the parts produced the fix. That is what the vocabulary is for: it is not terminology for its own sake, it is a way of decomposing a problem so the answer becomes visible.

What beginners get wrong

  • Using threat and vulnerability interchangeably. They are opposite ends of the relationship. Apply the test above: fixable by you means vulnerability.
  • Calling every attacker a "hacker" and every hacker a criminal. The word covers the professional this course trains you to be. The next chapters separate the classes properly.
  • Treating "zero-day" as a synonym for "very serious". It means unknown to defenders and therefore unpatched. Severity is a separate axis.
  • Reporting a vulnerability's severity as if it were the client's risk. Severity is intrinsic; risk adds threat and impact in that organisation's context. A critical flaw in a system they do not run is not their emergency.
  • Confusing exploit and payload. The exploit is the way in; the payload is what happens next. The same exploit can carry very different payloads, so the way in does not determine the harm.
  • Forgetting the asset. Without naming what is being protected, no statement about risk means anything.
munotes.in23

The Vocabulary: Asset, Threat, Vulnerability, Exploit and Risk

Quick revision

  • Asset (what you protect), vulnerability (a weakness in it, yours to fix), threat (a potential cause of harm, out in the world), threat actor (a specific one, with motivation, capability, persistence), attack surface (all the points of possible entry), exploit (the means of using a vulnerability), payload (what is done once in), attack (the event), zero-day (unknown and unpatched, a statement about knowledge), risk (likelihood times impact), control or mitigation (what reduces risk).
  • One sentence: a threat actor uses an exploit against a vulnerability to compromise an asset, and how much you should care is the risk.
  • Risk = Threat x Vulnerability x Impact, read as switches: if any factor is near zero, risk is low.
  • The test: fixable by changing your own systems means vulnerability; something that might come at you means threat.

Test yourself

  1. Define vulnerability, threat and exploit, and state the relationship between them in one sentence.

A vulnerability is a weakness in a system that could be taken advantage of; a threat is a potential cause of an unwanted incident; an exploit is the means of taking advantage of a vulnerability. A threat actor uses an exploit against a vulnerability to compromise an asset.

  1. Why is a critical vulnerability not automatically a high risk?

Because risk combines the vulnerability with the likelihood of a threat actor exploiting it and the impact if they do. A severe flaw in software the organisation does not run, or in an asset of no value, carries little risk despite its intrinsic severity.

  1. Give the test that distinguishes a threat from a vulnerability, and apply it to "our staff click on links in emails".

If it is something you could fix by changing your own systems, processes or people, it is a vulnerability; if it is something that might come at you from outside, it is a threat. Staff clicking links is a vulnerability, addressed by training and technical controls; criminals sending phishing emails is the threat.

munotes.in24

The Vocabulary: Asset, Threat, Vulnerability, Exploit and Risk

  1. What does "zero-day" actually describe, and what does it not?

It describes the defenders' state of knowledge: the vulnerability is unknown to them and therefore unpatched. It does not describe severity, so a known and patched flaw may be far more serious than a given zero-day.

  1. Distinguish an exploit from a payload.

The exploit is the technique that takes advantage of the vulnerability to gain entry or execution; the payload is what is carried out once that succeeds. The same exploit can deliver different payloads, so the method of entry does not by itself determine the harm.

Contents This chapter on its own page

munotes.in25

Chapter Six

The CIA Triad, and Which Property Each Attack Breaks

Syllabus topic Module 1, "Foundations of Ethical Hacking and Cyber Terminology: Study core terminology"

In one line

Security protects three properties: confidentiality (only the right people can read it), integrity (it has not been altered), and availability (it is there when needed). Every attack breaks at least one, and every control protects at least one.

In examination wording: the CIA triad is the standard model of information security objectives. Confidentiality is the property that information is not made available or disclosed to unauthorised individuals, entities or processes; integrity is the property of accuracy and completeness, that information has not been altered in an unauthorised manner; availability is the property of being accessible and usable on demand by an authorised entity.

Why three, and why this is the most useful model in the book

The triad is useful because the three questions it poses do not overlap, and because a security control almost never serves all three equally. Encryption protects confidentiality and does nothing for availability. A backup protects availability and, done carelessly, harms confidentiality by making a second copy of your secrets. A digital signature protects integrity without hiding anything at all. So naming the property under attack immediately narrows which controls could possibly help.

That is the practical payoff, and it is why this chapter is placed before any technique. When you meet an unfamiliar attack in a later chapter, or in the examination, or in a job, ask one question: which of the three does it break? The answer tells you what family of defence applies, and it is usually enough to reason your way to a sensible answer even about an attack you have never seen.

Confidentiality

Information is available only to those authorised to have it.

What breaks it: eavesdropping on a network (sniffing), stealing a database, a weak or reused password, an access-control flaw that returns another user's record, a misconfigured storage bucket left public, shoulder-surfing, an insider copying files, a leaked backup.

What protects it: encryption in transit and at rest, access control and authorisation checks, least privilege, strong authentication, classification of data so people know what is sensitive, and secure disposal so old media do not leak.

The characteristic failure: confidentiality is the property you cannot restore. Once information has been disclosed you can punish, apologise and improve, but you cannot make the reader forget. That asymmetry is why confidentiality controls are preventive rather than corrective, and why a breach notification exists at all.

Integrity

Information is accurate and complete, and has not been altered by anyone unauthorised.

What breaks it: a man-in-the-middle altering a message in transit, malware editing records, an SQL injection that updates a row, a price field trusted from the browser, an attacker changing a log to hide their tracks, and, importantly, accidental corruption: a failing disk, a truncated transfer, a bug.

munotes.in26

The CIA Triad, and Which Property Each Attack Breaks

What protects it: hashes and checksums to detect change, digital signatures and message authentication codes to detect unauthorised change, access controls on writing, input validation, database constraints and transactions, version control, and integrity monitoring on important files.

The characteristic failure: an integrity breach can be invisible. A stolen file is gone; an altered file is still there, looking normal, and every decision made from it afterwards is wrong. That is why detection matters as much as prevention here, and why a system that cannot prove its data is unaltered has an integrity problem even if nobody has attacked it.

Availability

The information and the systems are usable when an authorised person needs them.

What breaks it: a denial-of-service attack, ransomware encrypting the files, deletion of data, hardware failure, a power cut, a misconfiguration that takes a service down, a dependency that disappears, and an overload of perfectly legitimate traffic.

What protects it: redundancy and failover, capacity planning, backups that are tested and stored offline, rate limiting and filtering, upstream scrubbing for volumetric attacks, patching to prevent crashes, and monitoring so an outage is noticed before the customers notice.

The characteristic failure: availability is the property most often broken by accident rather than malice, and it is the property whose loss the business feels within minutes. It is also the one where the defence is least like the others: you cannot encrypt your way to availability, and adding security controls can reduce it, which is the tension in the next section.

The tension between the three

The three pull against one another, and an honest answer says so.

  • Encrypt a database and lose the key: confidentiality is perfect and availability is zero.
  • Lock an account after three wrong passwords, and you have protected confidentiality at the cost of availability, because an attacker can now lock out legitimate users deliberately.
  • Keep many backups for availability, and you have multiplied the places from which confidentiality can be lost.
  • Add integrity checks everywhere and the system slows, which at some point is an availability problem.

Security is therefore not "maximise all three" but a set of deliberate trade-offs, made differently for different assets. A hospital's patient records lean hard toward availability (a doctor must read them in an emergency); a country's intelligence files lean hard toward confidentiality. The examinable point: the right balance is a property of the asset, not a universal answer.

Two more properties the triad leaves out

The three-word model has a gap that examiners like to probe, so know the two words that fill it.

Authenticity. That something is genuine and from the claimed source. Integrity says the message was not altered; authenticity says who wrote it. They are different: an attacker can send you a brand-new message, perfectly intact, pretending to be your bank. Integrity is satisfied and you are still deceived. Authenticity is provided by authentication, digital signatures and certificates.

munotes.in27

The CIA Triad, and Which Property Each Attack Breaks

Non-repudiation. That the sender cannot later deny having sent it. This is stronger than authenticity, because it must convince a third party, not just the recipient. A message authentication code gives authenticity between two parties who share a key, but not non-repudiation, because either of them could have produced it; a digital signature, using a private key only one party holds, does give it. Section 3A and the electronic-signature scheme of the IT Act are the Indian legal form of the same idea.

Together these are sometimes called the "five pillars" (with the triad), and a strong answer names them.

A worked example: one system, three failures

A college runs an online examination portal holding question papers, student answers and results.

A confidentiality failure. A student finds that changing a number in the results URL shows another student's marksheet. Nothing was altered and the system stayed up; the property broken is confidentiality alone. The control that failed was authorisation, and the fix is a server-side check that the logged-in user owns the record.

An integrity failure. A student alters their submitted answer after the deadline through a flaw that trusts a timestamp sent by the browser. Nothing was disclosed and the system stayed up; the property broken is integrity. The controls that failed were input trust and write access, and the fix is a server-authoritative timestamp plus an append-only audit record.

An availability failure. On results day the portal is flooded and nobody can log in. Nothing was read and nothing was altered; the property broken is availability. The controls that failed were capacity and rate limiting, and the fix is caching, capacity and filtering.

And one attack that breaks two. An attacker intercepts and modifies a result in transit: confidentiality (they read it) and integrity (they changed it) both go, which is why a man-in-the-middle is treated as more serious than passive sniffing.

Notice how naming the property led straight to the family of control in every case. That is the working method this chapter is teaching.

Mapping the rest of the book

Attack (chapter later in this book)Property broken
Sniffing, passive eavesdroppingConfidentiality
Man-in-the-middle that alters trafficConfidentiality and integrity
ARP poisoning, DNS spoofingIntegrity of the network's answers, then confidentiality
Password attacks, credential stuffingConfidentiality (then whatever the account can reach)
SQL injection reading dataConfidentiality
SQL injection updating or deleting dataIntegrity, and availability if destructive
Cross-site scripting stealing a sessionConfidentiality
Denial of service, ransomwareAvailability
DefacementIntegrity
Log tampering by an intruderIntegrity, and it is what makes detection fail
munotes.in28

The CIA Triad, and Which Property Each Attack Breaks

What beginners get wrong

  • Thinking security means confidentiality. Availability failures are the ones a business notices first, and integrity failures are the ones that do lasting damage because they are invisible.
  • Treating the three as independent. They trade off. A control for one can harm another, and account lockout is the classic example.
  • Confusing integrity with authenticity. Integrity says unaltered; authenticity says from whom. A forged message can have perfect integrity.
  • Assuming a MAC gives non-repudiation. It does not, because both parties share the key and either could have produced it. A digital signature does.
  • Forgetting accidental causes. A failing disk breaks integrity and a power cut breaks availability with no attacker involved. Security controls must handle both.

Quick revision

  • Confidentiality: only authorised parties can read it. Broken by sniffing, weak access control, theft. Protected by encryption, access control, least privilege. Cannot be restored once lost.
  • Integrity: information is accurate and unaltered by anyone unauthorised. Broken by tampering, injection, malware, and by accident. Protected by hashes, signatures, write controls, validation, monitoring. Failures can be invisible.
  • Availability: usable on demand by authorised users. Broken by denial of service, ransomware, deletion, failure, overload. Protected by redundancy, capacity, backups, rate limiting, monitoring.
  • The three trade off against each other; the right balance depends on the asset.
  • Authenticity (from the claimed source) and non-repudiation (the sender cannot deny it) fill the gap the triad leaves. A MAC gives authenticity, not non-repudiation; a digital signature gives both.
  • The working method: when you meet a new attack, ask which property it breaks, and the family of defence follows.

Test yourself

  1. Name the three properties of the CIA triad and give one attack that breaks each.

Confidentiality, broken by network sniffing or an access-control flaw that reveals another user's data; integrity, broken by a man-in-the-middle altering a message or an injection that updates a record; availability, broken by a denial-of-service attack or ransomware.

  1. Why is an integrity breach often more damaging than a confidentiality breach, despite attracting less attention?

Because it can be invisible: the data is still present and looks normal, so the organisation keeps making decisions from information that is wrong. A disclosure is at least discovered; an undetected alteration keeps causing harm.

  1. Give an example of a control that protects one property at the expense of another.

Account lockout after repeated failed logins protects confidentiality by stopping password guessing, but harms availability, because an attacker can deliberately lock legitimate users out. Encryption without reliable key management similarly protects confidentiality while risking total loss of availability.

  1. Distinguish integrity from authenticity, and say which of a MAC and a digital signature provides non-repudiation.
munotes.in29

The CIA Triad, and Which Property Each Attack Breaks

Integrity means the information has not been altered; authenticity means it genuinely comes from the claimed source, so a forged but intact message satisfies integrity and fails authenticity. A message authentication code gives authenticity between two parties sharing a key but not non-repudiation, since either could have produced it; a digital signature, made with a private key only the signer holds, provides non-repudiation.

  1. A ransomware attack encrypts a hospital's records and the attackers also copy them first. Which properties are broken?

Availability, because the records cannot be used when needed, and confidentiality, because copies have been taken. Integrity is threatened as well if the restored data cannot be proved unaltered.

Contents This chapter on its own page

munotes.in30

Chapter Seven

Hacker Classes, Hacktivism and the Types of Hacking

Syllabus topic Module 1, "Foundations of Ethical Hacking and Cyber Terminology: Study core terminology including hacking types, hacker classes, hacktivism"

In one line

Hackers are classified by whether they have permission, not by how skilled they are. A white hat tests with authorisation; a black hat attacks without it; a grey hat acts without permission but usually without malice, which is well meant and still unlawful.

In examination wording: hackers are commonly classified by the lawfulness and intent of their activity. White-hat hackers (ethical hackers) test systems with the owner's authorisation to improve security; black-hat hackers gain unauthorised access for personal gain, damage or other criminal purpose; grey-hat hackers act without authorisation but typically without malicious intent, often disclosing what they find. Related categories include script kiddies, hacktivists, insiders and state-sponsored actors.

Why the popular classification is nearly useless, and how to fix it

The familiar "hat" scheme comes from old Western films, where the hero wore white and the villain black. As popular shorthand it is harmless; as a professional definition it fails, because it appears to classify people by character, and character is not something a court, a client or an examiner can assess.

The fix is the one the law already made for us in the previous chapters. Section 43 of the IT Act turns on a single fact: permission of the owner. So classify by that, and the scheme becomes precise, testable and consistent with the statute:

ClassPermission?Typical intentLegal position
White hatYes, written and scopedImprove the owner's securityLawful
Black hatNoGain, damage, disruptions.43 and, with dishonesty, s.66
Grey hatNoCuriosity, reputation, often to warns.43 applies; good motive is not a defence

Read down the "permission" column and you have the whole distinction. Everything else, skill, tools, motive, is secondary detail.

White hat: the ethical hacker

A white hat tests systems with the owner's authorisation, within an agreed scope, to find weaknesses before somebody hostile does, and reports them to the owner rather than using or publishing them. This is the role this entire course trains you for, and its defining features are the three documents of the earlier chapter: an authorisation, a scope, and rules of engagement.

Two things a white hat is not. They are not necessarily more skilled than a black hat; the distinction is not competence. And they are not merely "a hacker who is nice about it"; the discipline is procedural, and a tester who strays outside scope is not a white hat who made a mistake, they are unauthorised for that system.

Black hat: the criminal attacker

A black hat gains unauthorised access for their own purposes: money, disruption, theft of information, damage, or occasionally simple vandalism. They are the threat actor the rest of this book teaches you to anticipate.

munotes.in31

Hacker Classes, Hacktivism and the Types of Hacking

It is worth being precise about motive, because "for fun" is an outdated picture. Most serious attacks today are economically motivated and organised: ransomware operations, fraud, and the theft and sale of data are businesses with specialisation, tooling and support functions. A defender who imagines a lone teenager will build the wrong defences against an adversary that behaves like an industry.

Grey hat: the one the examiner asks about

A grey hat acts without authorisation but without clear malicious intent. The archetype probes a stranger's website out of curiosity, finds a flaw, takes nothing, and emails the owner to tell them.

This is the class worth thinking about carefully, because students instinctively feel it must be acceptable. It is not, and the reason is precisely the chapter on section 43: liability turns on the absence of permission, and the section does not ask about motive, damage or what you did afterwards. Good intent may matter to whether anyone pursues the matter, and it negates the dishonesty that section 66 requires, but it does not make the access lawful.

There is also a practical trap. A grey hat who reports a flaw has just told an organisation, in writing, that they accessed its systems without permission. Some organisations respond with thanks; some respond with lawyers. The finder has no contract, no scope, and no safe harbour.

The professional route to doing exactly what a grey hat wants to do is the bug bounty or a written scope: permission granted in advance, which converts the same activity into authorised testing. That chapter comes later, and this is the problem it solves.

The other categories worth naming

Script kiddie. Someone who uses tools written by others without understanding them. The term is dismissive about skill, and it should not be dismissive about risk: the tools are genuinely powerful, and an unskilled attacker running a working exploit against an unpatched server succeeds exactly as well as a skilled one. Defences are not improved by the attacker's ignorance.

Hacktivist. Someone who attacks or defaces systems to make a political or social point rather than for money. Common forms are website defacement (an integrity attack), denial of service as protest, and the leaking of documents. Legally there is nothing special about hacktivism: the acts are the same acts under section 43, and a cause does not supply permission. The category matters for a defender because it changes targeting: hacktivists choose targets for visibility and symbolism, so an organisation can become a target for what it represents rather than for what it holds.

Insider. Someone who already has legitimate access and abuses it, or exceeds it. Insiders are dangerous because most defences face outward, and because an insider's activity looks like ordinary work. They divide into the malicious (grievance, money, espionage) and the negligent, who cause harm without meaning to, and the second group is much larger. Controls are least privilege, separation of duties, monitoring of privileged actions, and a good leavers process.

munotes.in32

Hacker Classes, Hacktivism and the Types of Hacking

State-sponsored actor (sometimes called an advanced persistent threat). A government-backed group pursuing espionage or strategic disruption. What distinguishes them is not glamour but resources and patience: they can afford unknown vulnerabilities, they can wait months, and they do not give up because a first attempt failed. Most organisations are not their target; those that are cannot expect ordinary controls to suffice.

Suicide hacker. A term found in the CEH literature for an attacker indifferent to being caught, typically ideologically driven. It matters only because deterrence, which assumes the attacker fears consequences, does not work on them.

Types of hacking, by target

The syllabus also says "hacking types", which is usually taught as classification by what is attacked. Know the list, because it maps onto the structure of this book:

  • Network hacking: scanning, sniffing, man-in-the-middle, denial of service.
  • Web application hacking: injection, broken access control, cross-site scripting, session attacks.
  • System hacking: gaining access to a host, privilege escalation, persistence.
  • Wireless hacking: attacks on Wi-Fi authentication and encryption, rogue access points.
  • Social engineering: attacks on people rather than machines.
  • Mobile and cloud: attacks on applications and configurations in those environments.

Each is a later section of this book, and each is bounded by the same authorisation rule.

A worked example: one flaw, four people

A shopping site has a flaw letting any logged-in user read another customer's order by changing a number in the address.

  • Anita is engaged under a signed scope naming that site. She finds it, proves it with two test accounts, and reports it with a fix. White hat. Lawful, because she had permission for that system.
  • Bala finds it uninvited and quietly orders goods against other people's accounts. Black hat. Section 43 applies at once, and his dishonest purpose brings in section 66.
  • Chandni finds it uninvited, looks at two orders to be sure it is real, takes nothing and emails the company. Grey hat. Well meant, still unauthorised: section 43 is engaged by the access, and her good motive is not a defence, though it negates section 66's dishonesty.
  • Dev reads about the flaw online and runs a ready-made script against the site without understanding it. Script kiddie, and legally a black hat: no permission, and the lack of skill changes nothing.

Same flaw, same technique, four positions, decided by permission and purpose.

What beginners get wrong

  • Classifying by skill. The classes are about authorisation. A highly skilled unauthorised tester is a black hat; a modestly skilled authorised one is a white hat.
  • Believing a grey hat is safe because they meant well. Section 43 does not ask about motive. Good intent may negate section 66's dishonesty and may influence whether anyone pursues it, but it does not make the access lawful.
  • Thinking hacktivism is a legal category. It describes motive, not lawfulness. The acts are the same offences; the cause supplies no permission.
  • Underestimating script kiddies. The tools work. Your unpatched server does not care how well the attacker understands them.
  • Defending only against outsiders. Insiders already have access, and the negligent insider is the commonest of all. Least privilege and monitoring exist for them.
  • Assuming state actors are everyone's problem. They are not, and building for them while ignoring phishing and patching is a misallocation.
munotes.in33

Hacker Classes, Hacktivism and the Types of Hacking

Quick revision

  • Classify by permission, not by character: white hat (authorised, scoped, reports to the owner), black hat (unauthorised, criminal purpose), grey hat (unauthorised, not clearly malicious, still liable under s.43).
  • Also: script kiddie (others' tools, no understanding, still dangerous), hacktivist (political motive, no legal difference, changes targeting), insider (malicious or, more often, negligent; least privilege and monitoring), state-sponsored (resources and patience).
  • Hacking types by target: network, web application, system, wireless, social engineering, mobile and cloud.
  • The lawful way to do what a grey hat does is a bug bounty or a written scope: permission in advance.

Test yourself

  1. On what basis are hacker classes properly distinguished, and why is skill the wrong basis?

On authorisation: whether the person has the owner's permission. Skill is the wrong basis because it has no bearing on lawfulness; a highly skilled unauthorised tester is a black hat, and section 43 turns on permission, not competence.

  1. A grey hat finds a flaw uninvited, takes nothing, and reports it. What is their legal position?

Section 43 is engaged, because they secured access without the owner's permission and the section requires neither damage nor dishonest intent. Their good motive negates the dishonesty section 66 requires and may influence whether the owner pursues the matter, but it does not make the access lawful.

  1. Why is hacktivism not a separate legal category, and why does it still matter to a defender?

Because the acts are the same offences under the Act and a political cause supplies no permission. It matters to a defender because it changes targeting: hacktivists select targets for symbolism and visibility, so an organisation may be attacked for what it represents rather than what it holds.

  1. Why should a script kiddie not be dismissed?

Because the tools they run were written by capable people and work regardless of the user's understanding. An unpatched system is compromised just as effectively by an unskilled attacker using a working exploit.

munotes.in34

Hacker Classes, Hacktivism and the Types of Hacking

  1. Which class of attacker do most outward-facing defences miss, and what controls address them?

Insiders, who already hold legitimate access and whose activity resembles ordinary work; the negligent insider is the most common. They are addressed by least privilege, separation of duties, monitoring of privileged actions, and a reliable leavers process.

Contents This chapter on its own page

munotes.in35

Chapter Eight

Types of Engagement: Black Box, White Box, Grey Box, Internal and External

Syllabus topic Module 1, "Foundations of Ethical Hacking and Cyber Terminology: Study core terminology including hacking types"; row 1, "security audits, penetration testing engagements, vulnerability assessments"

In one line

Engagements differ by how much the tester is told (black, white or grey box), where they start (external or internal), and whether the defenders know (announced or unannounced). Each choice buys something different, and none is simply better than the others.

In examination wording: penetration testing engagements are classified by the information provided to the tester, black box (no prior knowledge), white box (full knowledge including documentation and source), or grey box (partial knowledge, typically a standard user account); by the tester's starting position, external (from the internet) or internal (from within the network); and by whether the defending team is informed, which distinguishes an announced test from a red-team exercise.

Why the type is agreed before anything else

The type of engagement is not an administrative detail; it decides what the client learns and what they pay for. A client who asks for "a penetration test" without settling the type usually wants one thing and buys another. So this chapter sits with the vocabulary, before the techniques, because the first professional conversation of any engagement is about what kind of engagement it is.

There is a budget truth underneath it. A tester's time is finite. Every hour spent discovering something the client could simply have told you is an hour not spent looking for the flaw that matters. That single observation explains most of what follows.

Black box, white box, grey box

Black box. The tester is given a target and nothing else: no documentation, no credentials, no network diagram, no source. They must discover everything, exactly as an outside attacker would.

What it buys: realism. It answers "what could somebody with no inside knowledge achieve?" and it tests the organisation's exposure as it actually appears from outside.

What it costs: time, and coverage. A large part of the engagement is spent on reconnaissance, and anything the tester fails to discover is not tested at all. A black-box test that misses an application entirely reports nothing about it, and the client may wrongly read silence as safety.

White box. The tester is given everything relevant: architecture documents, network diagrams, configurations, credentials for each role, and often the source code.

What it buys: depth and coverage per rupee. No time is wasted on discovery, the tester can reason about the design rather than guessing at it, and whole classes of flaw (logic errors, weak cryptography, flawed access-control design) become findable because the tester can read how the system is meant to work. For a given budget it finds substantially more.

What it costs: realism, in a narrow sense. It does not measure how hard the system is to discover. It also demands trust and paperwork, because the client is handing over sensitive material.

munotes.in36

Types of Engagement: Black Box, White Box, Grey Box, Internal and External

Grey box. The middle, and the commonest in practice. The tester gets partial information, typically a standard user account and a description of the application, but not the source or the administrative credentials.

What it buys: a realistic simulation of the threat that matters most for many systems, the authenticated user who misbehaves, whether a genuine customer, a low-privileged employee, or an attacker who has already phished one account. Since most serious web findings (broken access control above all) are only visible to someone logged in, starting logged in is often the most productive choice.

Black boxGrey boxWhite box
Information givenNonePartial, usually a user accountFull: docs, configs, credentials, source
SimulatesAn outside attackerA user, or an attacker with a footholdAn informed insider, or a design review
Time on discoveryHighModerateAlmost none
Coverage per rupeeLowestGoodHighest
Finds design flawsRarelySometimesYes
Main weaknessWhat is not found is not testedBounded by the access givenDoes not measure discoverability

The professional's summary: black box measures exposure, white box measures security, grey box is the practical compromise. If a client wants to know how secure their application is, white or grey box finds more. If they want to know what an anonymous internet attacker can reach, black box answers that specific question.

External and internal

A separate axis, and often confused with the one above.

External testing starts from the internet, against the organisation's public-facing systems: websites, mail servers, VPN endpoints, anything reachable from outside. It answers "what can be reached and exploited from the internet?"

Internal testing starts from inside the network, as though the tester were an employee, a visitor who found a network socket, or, most realistically today, an attacker who has already compromised one workstation through phishing. It answers "if somebody gets a foothold, what then?"

Internal testing is the one clients skip and the one that most often produces alarming findings, because many networks are hard on the outside and soft in the middle: flat networks with no segmentation, shared administrative passwords, unpatched internal servers nobody exposed to the internet and therefore nobody worried about. Given that an initial foothold through phishing is realistic, testing only the perimeter measures the wrong thing.

Note that the axes combine: an internal grey-box test (inside the network, with a standard domain account) is a very common and very informative engagement.

Announced or unannounced, and the red team

The third axis is whether the defenders know.

In an announced test the security team knows it is happening, and often knows the tester's source addresses. This is normal, and it is what deconfliction in the rules of engagement is for. The point is to find vulnerabilities efficiently.

munotes.in37

Types of Engagement: Black Box, White Box, Grey Box, Internal and External

In an unannounced exercise, usually called a red team engagement, only a small number of people know. The objective shifts: instead of enumerating as many vulnerabilities as possible, the red team pursues a specific goal ("obtain access to the payroll database") by whatever authorised means, while the blue team (the defenders) responds without knowing it is an exercise. What is being tested is not the systems but the detection and response capability: were they noticed, how quickly, and what did the defenders do?

A purple team exercise runs the two together deliberately, with attackers and defenders sharing information in real time so that each attack technique is immediately checked against whether the defence sees it. It is less dramatic and often more useful, because it improves detection directly.

Audit, vulnerability assessment and penetration test: three different products

MU's row 1 names all three, and they are not synonyms.

Vulnerability assessmentPenetration testSecurity audit
QuestionWhat weaknesses exist?Can they actually be exploited, and how far?Do we comply with a standard or policy?
MethodLargely automated scanning, broadManual, with tooling, deepReview against a checklist or control set
OutputA list of findings by severityProven findings with evidence and impactA compliance position with gaps
Breadth vs depthBroad, shallowNarrow, deepBroad, procedural
ExploitationNoYes, within scopeNo

The examinable distinction: a vulnerability assessment tells you what might be wrong; a penetration test proves what actually is, and what it would cost you. A scanner reporting "this version has a known flaw" is a hypothesis; a tester demonstrating access is evidence. Both have value, and they are priced very differently for that reason.

A client who asks for a penetration test and is sold an automated scan has been badly served, and a client who wants an inventory of every missing patch does not need a penetration test to get one.

A worked example: choosing the type

A college wants to secure its new student portal and has a limited budget. Work through the choices:

  • What worries them most? Students reading or altering each other's results. That is an authenticated-user threat, so a grey-box test with two student accounts targets it directly. A black-box test would spend its budget rediscovering the login page.
  • External or internal? The portal is public, so external. But the same conversation should ask whether a compromised staff workstation could reach the results database directly, which is an internal question and may matter more.
  • Announced? Yes. The college has no dedicated security team to test, so a red-team exercise would measure a capability that does not exist. Announced testing spends the budget on finding flaws.
  • Which product? A penetration test for the portal, because they want to know what is actually exploitable, plus possibly a vulnerability assessment across the wider estate for breadth at low cost.
munotes.in38

Types of Engagement: Black Box, White Box, Grey Box, Internal and External

The reasoning throughout is the same: match the engagement to the threat the client actually faces and the decisions they need to make.

What beginners get wrong

  • Assuming black box is the "real" test. It is the most realistic simulation of an anonymous outsider and the least efficient way to find flaws. What it fails to discover, it fails to test.
  • Treating white box as cheating. It finds more per rupee and is the only way to catch design and logic flaws. Realism is one objective among several, not the only one.
  • Confusing the information axis with the position axis. Black and white box describe what the tester is told; external and internal describe where they start. An internal white-box test is perfectly coherent.
  • Buying a red team without a blue team. If nobody is watching, an unannounced exercise measures a detection capability that does not exist, and the money is better spent on finding vulnerabilities.
  • Using "vulnerability assessment" and "penetration test" interchangeably. One lists potential weaknesses, largely automatically; the other proves exploitability and impact, manually. The deliverables and the prices differ accordingly.
  • Testing only the perimeter. Given that a phishing foothold is realistic, an internal test usually tells the client more than another external scan.

Quick revision

  • Information axis: black box (nothing given, realistic, slow, misses what it cannot find), white box (everything given, deepest coverage, finds design flaws), grey box (a user account, the practical middle, targets the authenticated-user threat).
  • Position axis: external (from the internet, the perimeter) and internal (from inside, simulating a foothold; usually the more revealing).
  • Awareness axis: announced (efficient vulnerability finding) against red team (unannounced, goal-driven, tests detection and response). Purple team runs attack and defence together to improve detection directly.
  • Products: vulnerability assessment (broad, automated, what might be wrong), penetration test (deep, manual, proves exploitability), security audit (compliance against a standard).
  • Choose the type from the threat the client faces and the decision they need to make.

Test yourself

  1. Distinguish black-box, white-box and grey-box testing, and say which gives the most coverage for a fixed budget.

Black box gives the tester no prior information, white box gives full information including documentation and source, and grey box gives partial information such as a standard user account. White box gives the most coverage for a fixed budget, because no time is spent on discovery and design flaws become findable.

  1. What is the main weakness of a black-box test?

Anything the tester fails to discover is not tested at all, and the client may wrongly read the silence as evidence of safety. It also spends a large share of the budget on reconnaissance rather than on finding flaws.

munotes.in39

Types of Engagement: Black Box, White Box, Grey Box, Internal and External

  1. Why is internal testing often more revealing than external testing?

Because many networks are hardened at the perimeter and weak internally, with flat segmentation, shared administrative credentials and unpatched internal systems. Since an attacker gaining a foothold through phishing is realistic, testing only the perimeter measures the wrong threat.

  1. How does a red-team exercise differ in objective from an ordinary penetration test?

An ordinary announced test aims to find as many exploitable vulnerabilities as possible. A red-team exercise is unannounced and goal-driven, and what it tests is the defenders' detection and response capability: whether the activity was noticed, how quickly, and what was done.

  1. State the difference between a vulnerability assessment and a penetration test.

A vulnerability assessment is broad and largely automated and reports weaknesses that may exist; a penetration test is deeper and manual and proves which weaknesses are actually exploitable and what impact they would have, with evidence.

Contents This chapter on its own page

munotes.in40

Chapter Nine

The Five Phases of an Engagement: a Lifecycle Model

Syllabus topic Module 1, "Foundations of Ethical Hacking ... ethical hacking phases ... Prepare a structured lifecycle model of ethical hacking"

In one line

An engagement runs through five phases in order: reconnaissance, scanning, gaining access, maintaining access, and covering tracks. An attacker runs all five to stay hidden; an ethical hacker runs as far as the scope requires to prove risk, preserves the evidence, and reports.

In examination wording: the ethical hacking lifecycle is a structured, repeatable process comprising (1) reconnaissance, the gathering of information about the target; (2) scanning, the identification of live hosts, open ports and services; (3) gaining access, the exploitation of a weakness to obtain entry; (4) maintaining access, the retention of that foothold; and (5) covering tracks, the concealment of the activity. Each phase is bounded by the engagement's authorisation and scope and is met by a corresponding defensive control.

Why a lifecycle model at all

Two reasons, one practical and one for the marks.

Practically, a model stops the work being a random walk. Testing without a process means poking at whatever catches the eye, and the result is uneven: three hours on an interesting but unimportant service while an exposed administrative interface sits undiscovered. A named sequence makes the work repeatable (another tester would cover the same ground) and complete (you can say what you did and did not do), and it makes the report readable, because the reader can follow the same order.

For the marks, MU asks you to prepare the model, which means drawing it and defending it, not listing five words. A model that lists five words is worth very little; a model that carries, for each phase, what happens, where authorisation binds it, and how a defender meets it, is the answer.

The provision broken down: the five phases

Phase 1: Reconnaissance

Gathering information about the target before, or with minimal, contact. It divides into passive reconnaissance, which uses third parties and never touches the target's systems (search engines, public records, social media, WHOIS), and active reconnaissance, which does touch them (resolving names against their servers, a light probe).

The aim is a map: domain names, addresses, technologies, people, email formats, third-party suppliers. Chapters later in this module cover it in detail.

This is the phase beginners undervalue and professionals rate highest, because everything after it is narrowed by what it finds. An attacker who knows your staff names, your technology versions and your forgotten test server has reduced a vast problem to a small one before sending a single suspicious packet.

The authorisation note: passive reconnaissance reads what is already public and touches nothing, so it does not engage section 43. Active reconnaissance does touch the target and does.

Phase 2: Scanning

Turning the map into a list of live hosts, open ports, running services and their versions. Host discovery first, then port scanning, then service and version detection, and often operating-system fingerprinting.

munotes.in41

The Five Phases of an Engagement: a Lifecycle Model

The output of this phase is the input to vulnerability analysis: a service and a version is what you look up to find known flaws. "Apache 2.4.x on port 443" is a sentence you can act on; "there is a web server somewhere" is not.

The authorisation note, and it is the important one: scanning plainly touches the target's systems and is an act under section 43. This is the first phase that unambiguously requires written permission, and students routinely believe the line is crossed later, at "gaining access". It is not.

Phase 3: Gaining access

Using a weakness found in scanning to obtain entry: a weak or default credential, an unpatched service with a known flaw, an injection flaw in an application, a misconfiguration.

This is where a risk stops being theoretical. A report that says "this version has a known critical flaw" is a hypothesis; a report that says "we used it to read the configuration file, here is the evidence" is proof, and it is far harder for an organisation to defer.

The discipline for an ethical hacker is least intrusion: gain access to the depth the scope allows, capture the evidence that proves the finding, and stop. The goal is demonstration, not conquest.

Phase 4: Maintaining access

Keeping the foothold, as a real attacker would, to show what a persistent intruder could reach: other systems, more data, higher privilege. Attackers do this with backdoors, additional accounts, scheduled tasks and rootkits.

In an ethical engagement this phase happens only if the scope permits it, everything installed is logged and removed afterwards, and the purpose is to demonstrate impact rather than to establish a presence. Many engagements stop before this phase entirely, and the report simply notes what a real attacker would have attempted next.

Phase 5: Covering tracks

An attacker's fifth phase is concealment: deleting or editing logs, hiding files, clearing command history, using timestamps that blend in. The purpose is to remain undetected so that phases three and four keep paying.

An ethical hacker inverts the spirit of this phase, and this is the single most important distinction in the chapter. They do not destroy the client's logs. They may test whether logging can be evaded, because "our logging did not record this" is a valuable finding, but they preserve the evidence, record precisely what they did and when, and hand it over. Cleaning up, for a tester, means removing the artefacts they introduced, not removing the record that they were there.

Understanding the attacker's version matters defensively, because it tells you what an intruder will attack: the logs are the record of the attack, so the logs are a target. That is the argument for centralised, append-only, off-host logging.

munotes.in42

The Five Phases of an Engagement: a Lifecycle Model

The lifecycle model, as a table you can reproduce

This is what MU asks you to prepare. Learn it in this shape and you can draw it under examination conditions.

PhaseWhat happensAuthorisation boundaryDefensive control
1. ReconnaissanceGather public information (passive) and light-contact information (active)Passive touches nothing; active touches the target and needs permissionReduce public footprint; monitor for unusual queries
2. ScanningFind live hosts, open ports, services and versionsPlainly an act under s.43; written permission requiredFirewall, close unused ports, intrusion detection
3. Gaining accessExploit a weakness to obtain entry and prove the riskOnly to the depth the scope allows; least intrusionPatching, strong authentication, input validation, least privilege
4. Maintaining accessRetain the foothold to demonstrate impactOnly if the scope permits; log everything and remove it afterEndpoint detection, integrity monitoring, hunting for persistence
5. Covering tracksAn attacker conceals; a tester preserves and documentsNever destroy the client's evidenceCentralised, append-only, protected logging

The third column is the thread from the law chapters running through every phase. The fourth column is the thread that runs into every later chapter of the book, and it is the subject of the next chapter.

A worked example

Sana is engaged to test one web server. The scope names a single host, permits exploitation to the minimum depth needed to prove a finding, and forbids persistence.

Reconnaissance. She reads the company's public site, notes the technology named in its page headers and a staff email format from a published address, and looks up the domain's DNS records. Nothing she has done touches the company's own systems.

Scanning. With the authorisation in hand she scans the one named host and finds three open ports; version detection shows an out-of-date web server on one of them.

Gaining access. She confirms the outdated version has a known flaw and uses it to read a configuration file. That is enough: the risk is proven. She captures the evidence with the sensitive values masked and goes no further.

Maintaining access. Out of scope, so she does not attempt it. The report records that a real attacker would have tried, and that the credentials in the configuration file would have allowed it.

Covering tracks. She preserves every log, records the exact times of each test so the client can separate her activity from a real attacker's, removes nothing, and hands over the evidence.

Her report then follows the same five headings, which is a second reason to internalise the model: it structures the work and the write-up alike.

munotes.in43

The Five Phases of an Engagement: a Lifecycle Model

What beginners get wrong

  • Believing an ethical hacker runs all five phases fully. They run as far as the scope requires to prove risk, often stopping in phase 3, and they never "cover tracks" against the client.
  • Skipping reconnaissance because it does not feel like hacking. It is the phase with the highest return, and the one whose omissions silently limit everything after it.
  • Thinking the legal line is crossed at phase 3. It is crossed at phase 2, and often in the active half of phase 1. Scanning is an act under section 43.
  • Treating the phases as strictly one-way. They loop: access to one system starts fresh reconnaissance and scanning from inside it. The linear order is the teaching model; real work spirals.
  • Listing five words as "the model". MU asks for a structured model. Without the authorisation boundary and the defensive control, it is a list, not a model.

Quick revision

  • Five phases: (1) reconnaissance, (2) scanning, (3) gaining access, (4) maintaining access, (5) covering tracks.
  • Reconnaissance splits into passive (third parties, touches nothing) and active (touches the target, needs permission).
  • Scanning is the first phase that plainly needs authorisation under s.43, not gaining access.
  • An ethical hacker stops where the scope says, practises least intrusion, and preserves evidence rather than destroying it; cleaning up means removing artefacts introduced, not removing the record.
  • The model to reproduce carries four columns: phase, what happens, the authorisation boundary, the defensive control.
  • The phases loop; the linear order is a teaching device.

Test yourself

  1. Name the five phases of an ethical hacking engagement in order, and say what each produces.

Reconnaissance (a map of the target from public and light-contact sources), scanning (live hosts, open ports, services and versions), gaining access (proven entry through a weakness), maintaining access (demonstrated persistence and reach), covering tracks (concealment by an attacker; preserved and documented evidence by a tester).

  1. At which phase is authorisation first clearly required, and why do students get this wrong?

At scanning, because scanning unambiguously touches the target's systems and is an act under section 43 of the IT Act. Students assume the line is crossed only at gaining access, but by then it has been crossed twice, since active reconnaissance can require permission too.

  1. How does an ethical hacker's handling of the fifth phase differ from an attacker's, and what does the attacker's version teach a defender?

An attacker deletes or edits logs and hides files to stay undetected. An ethical hacker preserves the client's logs, documents exactly what was done and when, and removes only the artefacts they introduced. The attacker's version teaches that logs are themselves a target, which is the argument for centralised, append-only, off-host logging.

munotes.in44

The Five Phases of an Engagement: a Lifecycle Model

  1. What four things should each phase carry in the lifecycle model MU asks you to prepare?

The phase name, what happens in it, the authorisation and scope boundary that applies to it, and the defensive control that detects or prevents it.

  1. Why is reconnaissance described as the highest-value phase?

Because it narrows a vast problem to a small one before any suspicious contact: knowing the technologies, people, email format and forgotten hosts determines what every later phase can achieve, and anything missed in reconnaissance silently limits the rest of the engagement.

Contents This chapter on its own page

munotes.in45

Chapter Ten

The Defender's Mirror: a Control for Every Phase

Syllabus topic Module 1, "Foundations of Ethical Hacking ... ethical hacking phases"; Course Outcome 5, "Recommend appropriate mitigation strategies and security hardening measures"

In one line

Read the five phases from the defender's side and each one becomes a place to detect or stop the attack. The attacker must succeed at every phase; the defender only has to break one. That asymmetry, in the defender's favour, is what makes security possible.

In examination wording: for each phase of the attack lifecycle there exist corresponding preventive, detective and corrective controls; because an attack requires the successful completion of a sequence of phases, interrupting any single phase defeats the attack, which is the principle underlying defence in depth and the kill-chain model.

Why this chapter exists

It is easy to read a book of attacks and come away feeling that defence is hopeless: there are so many techniques, and the attacker needs only one to work. That impression is wrong, and inverting it is the most valuable idea in this module.

The attacker's position is worse than it looks. To do real harm they must reconnoitre successfully, and find something exploitable, and exploit it, and hold the position, and avoid being noticed. Fail at any one and the attack does not complete. The defender, meanwhile, needs only to make one of those steps fail, and has the additional advantage of owning the ground: they can change the systems, watch the logs, and prepare in advance.

That is the kill chain idea, and it is why controls are arranged in layers rather than as a single wall. It is also why "we have a firewall" is not a security posture: a firewall addresses one phase.

The three kinds of control

Before the mirror itself, the vocabulary examiners use for controls.

  • Preventive controls stop the thing happening: a firewall blocking a port, a patch removing a flaw, input validation rejecting bad data, least privilege denying an action.
  • Detective controls notice that it happened or is happening: intrusion detection, log monitoring, file integrity checking, alerting on anomalies.
  • Corrective controls limit or repair the damage afterwards: backups, incident response, isolating a host, revoking credentials.

A mature defence has all three at each phase, because prevention eventually fails. Two further classifications are worth naming: deterrent controls discourage an attempt (warning banners, visible monitoring), and compensating controls substitute for one that cannot be implemented (extra monitoring where a legacy system cannot be patched).

The examinable point is that these are categories of purpose, not categories of technology. The same log file is detective when monitored, corrective when used in an investigation, and worthless when nobody reads it.

Phase 1: Reconnaissance, mirrored

What the attacker is doing. Building a picture from public sources, and probing lightly.

Why it is hard to prevent. You cannot stop somebody reading your website, searching for your staff, or querying the public DNS. Reconnaissance is mostly invisible and largely lawful.

munotes.in46

The Defender's Mirror: a Control for Every Phase

Preventive. Reduce what is public rather than trying to stop it being read: suppress version numbers in headers and error pages, avoid naming exact software versions in job advertisements, publish role-based email addresses where possible, strip metadata from published documents, and above all inventory every subdomain and retire the forgotten ones, because a forgotten host is an unpatched host.

Detective. Monitor for unusual patterns of queries, watch certificate-transparency logs for certificates issued for your names, and set alerts for your domains and brand appearing in newly registered look-alike domains, which is often the first sign of a phishing campaign being prepared.

Corrective. Take down exposed material; where credentials or keys have leaked publicly, rotate them.

Phase 2: Scanning, mirrored

What the attacker is doing. Enumerating hosts, ports, services and versions.

Preventive. Default-deny at the perimeter, so unsolicited traffic is dropped and ports appear filtered rather than answering; close unused ports and disable unused services, since every listening service is attack surface; suppress banners; segment the network so a scan from one place cannot see everything.

Detective. This is the phase where detection is genuinely good, and it is a point students underrate. A port scan is a distinctive pattern, many connection attempts across many ports from one source in a short time, and it is exactly what an intrusion detection system is tuned for. The "stealthy" half-open scan avoids some connection logs and is loud to a network sensor.

Corrective. Block or rate-limit the source; treat a scan as an indicator and check whether anything it found is exposed.

The honest caveat: scanning is so constant on the public internet that alerting on every scan produces noise. The value is in noticing scanning that is targeted, or that comes from inside the network, which is a serious indicator.

Phase 3: Gaining access, mirrored

What the attacker is doing. Exploiting a weakness: an unpatched service, a weak credential, an injection flaw, a misconfiguration.

Preventive, and this is where the money should go. Patch promptly, prioritised by severity and exposure. Enforce strong authentication and, above all, multi-factor authentication, which defeats the commonest route of all, a stolen or guessed password. Validate input and use parameterised queries. Apply least privilege so that what is reached is limited. Remove default accounts and change default credentials. Harden configurations against a published baseline.

Detective. Failed-login monitoring and impossible-travel alerts; web application firewall alerts; alerts on unexpected process execution; anomalies in application logs such as a spike of errors from one source.

Corrective. Incident response: isolate the host, revoke and rotate the credentials, rebuild from clean media, restore from backup.

munotes.in47

The Defender's Mirror: a Control for Every Phase

Phase 4: Maintaining access, mirrored

What the attacker is doing. Establishing persistence so the foothold survives a reboot, and moving laterally to reach more.

Preventive. Least privilege again, because most persistence mechanisms need elevated rights; application allow-listing so unknown programs cannot run; network segmentation so a foothold in one place cannot reach the rest; separate administrative accounts so a compromised everyday account does not confer administrative power.

Detective, and this is the richest phase for detection. Persistence is noisy if you are looking: new or modified auto-start entries, new services and scheduled tasks, new accounts, new administrative group memberships, unexpected outbound connections at odd hours, and lateral-movement patterns such as one workstation authenticating to many others. Endpoint detection and response exists largely for this phase, and threat hunting means deliberately looking here rather than waiting for an alert.

Corrective. Remove the persistence, rotate every credential the attacker could have reached, and, where a kernel-level compromise is confirmed, rebuild rather than clean.

Phase 5: Covering tracks, mirrored

What the attacker is doing. Deleting or editing logs, clearing history, hiding files, so that phases three and four keep paying.

Preventive, and it is the decisive control. Ship logs off the host, immediately, to a central system the compromised host cannot write to. An attacker who owns a machine can edit anything on it, so any log that stays local is only as trustworthy as the host. Centralised, append-only logging with restricted access defeats the entire phase, because the attacker would have to compromise the logging system as well.

Detective. Alert on the act of covering tracks itself, which is a high-quality signal precisely because it is rare in normal operation: the audit log being cleared, logging being stopped, a large deletion in a log directory, or a gap in a log stream that should be continuous. Time synchronisation across hosts matters here, so events can be correlated.

Corrective. Preserve what remains, treat it as evidence, and involve the people who handle incidents properly.

The mirror, as a table

PhasePreventiveDetectiveCorrective
ReconnaissanceReduce public footprint; retire forgotten hosts; suppress versionsWatch for look-alike domains, certificate logs, odd query patternsTake down exposed material; rotate leaked secrets
ScanningDefault deny and drop; close unused ports; segmentIntrusion detection on scan patterns; alert on internal scanningBlock the source; verify what was exposed
Gaining accessPatch; multi-factor authentication; input validation; least privilege; no defaultsFailed-login and anomaly alerts; application and firewall alertsIsolate, revoke, rebuild, restore
Maintaining accessLeast privilege; allow-listing; segmentation; separate admin accountsPersistence and lateral-movement hunting; endpoint detectionRemove persistence; rotate credentials; rebuild
Covering tracksCentralised, append-only, off-host loggingAlert on log clearing, logging stopped, stream gapsPreserve evidence; formal incident response
munotes.in48

The Defender's Mirror: a Control for Every Phase

A worked example, read as a defender

An attacker phishes an employee, gets their password, logs into the VPN, finds an unpatched internal server, gains administrator on it, installs a scheduled task for persistence, and clears the event log.

Now ask where the defence could have broken the chain, and notice that any one of these would have been enough:

  • Multi-factor authentication on the VPN would have made the stolen password insufficient (phase 3 preventive).
  • Patching the internal server would have removed the escalation route (phase 3 preventive).
  • Network segmentation would have stopped the VPN reaching that server at all (phase 4 preventive).
  • An alert on the new scheduled task would have caught the persistence (phase 4 detective).
  • Off-host logging would have preserved the record the attacker deleted, and the clearing itself would have raised an alert (phase 5 preventive and detective).

Five independent opportunities against one attack. That is the asymmetry this chapter is about, and it is the answer to "there are too many attacks to defend against".

What beginners get wrong

  • Thinking defence must stop everything. It must break the chain once. Layers exist so that a single failure is survivable.
  • Spending everything on prevention. Prevention eventually fails; without detection you will not know, and without correction you cannot recover. Budget across all three.
  • Leaving logs on the host. A local log is only as trustworthy as the machine, and the machine is the thing that was compromised. Off-host logging is the control that defeats phase 5.
  • Treating a control as inherently one kind. A log is detective only if somebody reads it. Purpose, not technology, defines the category.
  • Alerting on everything. Internet-facing scanning is constant; alerting on all of it produces noise that hides the signal. Tune for targeted and internal activity.
  • Forgetting that reconnaissance is mostly unpreventable. The control there is reducing what is public, not trying to stop people reading it.

Quick revision

  • The attacker must complete every phase; the defender need break only one. That asymmetry is the kill-chain idea and the basis of defence in depth.
  • Controls are preventive (stop it), detective (notice it), corrective (limit and repair), plus deterrent and compensating. The categories describe purpose, not technology.
  • Reconnaissance: cannot be prevented, so reduce the public footprint and retire forgotten hosts; watch for look-alike domains.
  • Scanning: default deny and drop, close unused ports, segment; detection is strong here, and internal scanning is a serious indicator.
  • Gaining access: the phase that deserves the budget. Patch, multi-factor authentication, input validation, least privilege, no defaults.
  • Maintaining access: the richest phase for detection. Hunt for new persistence, new accounts, lateral movement.
  • Covering tracks: defeated by centralised, append-only, off-host logging; log clearing is itself a high-quality alert.
munotes.in49

The Defender's Mirror: a Control for Every Phase

Test yourself

  1. State the asymmetry between attacker and defender in the lifecycle model, and what follows from it.

The attacker must complete every phase successfully, while the defender needs to break only one. It follows that controls should be layered across the phases (defence in depth), so that the failure of any single control does not mean the failure of the defence.

  1. Distinguish preventive, detective and corrective controls, and give one of each for the gaining-access phase.

Preventive controls stop the event (patching, multi-factor authentication); detective controls notice it (failed-login and anomaly alerting); corrective controls limit and repair the damage (isolating the host, revoking credentials, restoring from backup).

  1. Which single control most directly defeats the covering-tracks phase, and why?

Centralised, append-only, off-host logging. An attacker who controls a host can alter anything stored on it, so only logs shipped immediately to a system the host cannot write to remain trustworthy; the attacker would have to compromise the logging infrastructure as well.

  1. Why is reconnaissance the phase least amenable to preventive control, and what is the defensive answer?

Because it largely uses public sources and third parties, which you cannot stop anyone reading, and much of it never touches your systems. The answer is to reduce what is public (suppress versions, strip metadata, retire forgotten subdomains) and to watch for indirect signals such as newly registered look-alike domains.

  1. Why is the maintaining-access phase described as the richest for detection?

Because persistence and lateral movement leave distinctive traces that are rare in normal operation: new auto-start entries, services, scheduled tasks and accounts, new administrative group memberships, and one host authenticating to many others. Threat hunting deliberately searches for these rather than waiting for an alert.

Contents This chapter on its own page

munotes.in50

Chapter Eleven

The Life of a Vulnerability

Syllabus topic Module 1, "Vulnerability Research and Disclosure Mechanisms: Understand vulnerability lifecycle"

In one line

A vulnerability has a life: it is introduced by a mistake, discovered by someone, reported, fixed, and disclosed. The dangerous part is the window between the moment an attacker could use it and the moment a given user is protected, and every practice in this area exists to make that window shorter.

In examination wording: the vulnerability lifecycle describes the stages through which a security weakness passes from its introduction into a product, through discovery, reporting, triage and remediation, to public disclosure and eventual patching by users; the interval during which the vulnerability is exploitable in practice is the window of exposure, and reducing it is the objective of coordinated disclosure and patch management.

Why a weakness has a "life" at all

It is tempting to think of a vulnerability as a fact: either the software is flawed or it is not. But from a security point of view what matters is not whether the flaw exists, it is who knows about it and what they have done about it. The same line of code is harmless while nobody knows, dangerous once an attacker knows, and harmless again once the user has patched, without the code changing at all between the first and second states.

So the useful model is a timeline, and the useful questions are about ordering: who found out first, how long before the vendor knew, how long before a fix existed, and how long before it was installed. Those four intervals are what the rest of this block is about.

The stages

1. Introduction. The flaw enters the software. Almost always it is an ordinary mistake by a competent developer: a missing bounds check, a wrong default, an authorisation check on one path and not another, a dependency added without review. Every vulnerability was once a bug nobody noticed.

Two things follow that students find surprising. First, the flaw may sit unexploited for years: it is live from the moment the code ships, whether or not anyone has found it. Second, secure development practices (code review, static analysis, threat modelling, memory-safe languages) act here, at the cheapest possible point, which is why "shift left" is more than a slogan: a flaw prevented at introduction costs a fraction of one patched in the field.

2. Discovery. Somebody finds it. Who finds it first is the single most consequential fact in the whole lifecycle:

  • The vendor's own team, through review, testing or fuzzing. Best case: the fix can be made quietly before anyone else knows.
  • A security researcher or bug-bounty participant, who will usually report it.
  • An academic, who may report it and will usually publish eventually.
  • An attacker, who will not report it. This is the worst case, and the flaw becomes a zero-day in use, with defenders unaware they are exposed.
munotes.in51

The Life of a Vulnerability

A flaw may be discovered independently by more than one party, and this is not a rarity. It is the fact that makes long disclosure delays risky: a vendor who takes a year to fix is not only keeping one researcher waiting, they are gambling that nobody else finds the same thing.

3. Reporting. The finder tells the vendor, through a security contact, a bug-bounty platform, or a coordinating body. The mechanics of doing this well, and the vendor's obligations, are the next chapter.

The quality of the report matters more than beginners expect: a reproducible report with clear steps and an assessment of impact gets triaged and fixed quickly, while a vague one sits in a queue.

4. Triage and remediation. The vendor confirms the flaw, works out how serious it is and what else is affected, and develops a fix. This is the stage that takes longest and the one outsiders understand least. A vendor must often fix the same flaw across several supported versions, test that the fix breaks nothing, and coordinate with downstream parties who ship their software inside other products.

That last point explains delays that look inexcusable from outside: a library flaw is not fixed when the library is fixed, but when every product embedding it has shipped an update, and some of those products are appliances on long release cycles.

5. Disclosure. The existence and usually the detail of the flaw is made public: an advisory is issued, a CVE identifier is assigned, and users are told to update. Ideally the fix and the advisory arrive together, so that the information that lets an attacker act arrives at the same moment as the means to be protected.

6. Patch availability, and then patch adoption. These are two different events and confusing them is a classic error. A fix existing does not protect anybody; a fix installed does. Between them sits testing, change control, maintenance windows, and in many organisations simple neglect. For appliances and embedded devices the gap can be permanent, because nobody ever updates them.

The two clocks

Put an attacker's knowledge and a defender's protection on the same timeline and the shape of the problem appears.

MomentWhat changes
IntroductionThe flaw is live, unknown to everyone
An attacker discovers itThe window of exposure opens. Defenders do not know they are exposed
Defenders learn of it (disclosure, or detection of an attack)Defenders can act, but there may be no fix yet
A fix is releasedProtection becomes possible
A given user installs the fixThe window closes, for that user only
munotes.in52

The Life of a Vulnerability

The period between an attacker knowing and a fix existing is the zero-day period: defenders are exposed and cannot patch, so the only defences are the generic ones, segmentation, least privilege, monitoring and, where the vendor offers one, a temporary workaround.

The period between a fix existing and a user installing it is, in aggregate, where most real-world compromise happens. Attacks overwhelmingly exploit known, patched vulnerabilities on unpatched systems, not zero-days. That is the most practically important sentence in this chapter, and it is why patch management is worth a chapter of its own later: the unglamorous discipline of installing fixes prevents more harm than any clever control.

A further consequence: public disclosure raises risk in the short term. Once details are published, the population capable of exploiting the flaw grows from a few to many, and exploitation of newly disclosed flaws typically rises sharply within days. This is not an argument against disclosure, which is what makes defenders able to act at all; it is the argument for having the fix ready first, and for patching quickly once it is.

A worked example

A flaw is introduced into a widely used library in January 2024 by a routine mistake.

  • January 2024 to March 2026: nobody knows. The flaw is live in every product embedding the library. Risk in practice is near zero, because no one is using it.
  • March 2026: an attacker finds it and uses it against a handful of targets. The window of exposure is now open and defenders do not know. This is a zero-day in use; the only defences are generic.
  • April 2026: a researcher independently finds it and reports it to the vendor. The vendor now knows, but there is still no fix.
  • May 2026: the vendor releases a fix, publishes an advisory and a CVE is assigned. Protection becomes possible. Exploitation attempts rise sharply in the following week as the details become public.
  • May to December 2026: organisations patch, at very different speeds. Each one's window closes when it patches, not when the vendor shipped. Some appliances are never updated and remain exposed indefinitely.

Now read off the lessons: the flaw was live for two years before it mattered; independent discovery is real; the fix existing protected nobody by itself; and the long tail of unpatched systems is where most of the eventual damage occurs.

What beginners get wrong

  • Confusing "a patch exists" with "we are protected". These are different events with a gap between them, and the gap is where most compromise happens.
  • Believing most attacks use zero-days. The great majority exploit known, patched flaws on systems that were not updated. Zero-days are rare and expensive; unpatched systems are everywhere.
  • Thinking a flaw is harmless until disclosed. It is live from introduction. Disclosure changes who can act, not whether the weakness exists.
  • Assuming a slow vendor is simply negligent. Fixing across supported versions, testing for regressions and coordinating with downstream vendors takes real time, particularly for a library embedded in other products.
  • Treating independent discovery as unlikely. It is common enough that it is the central risk in any long disclosure timeline.
  • Forgetting the cheapest point. Preventing introduction through review, analysis and safer languages costs far less than remediating in the field.
munotes.in53

The Life of a Vulnerability

Quick revision

  • Stages: introduction (an ordinary mistake, live from the moment it ships), discovery (by vendor, researcher, academic or attacker, and possibly by more than one independently), reporting, triage and remediation (slow for good reasons, especially for embedded libraries), disclosure (ideally with the fix), patch availability, and patch adoption.
  • Patch availability and patch adoption are different events; the window closes for each user only when that user patches.
  • The zero-day period is when an attacker knows and no fix exists; defences are generic (segmentation, least privilege, monitoring, workarounds).
  • Most real compromise exploits known, patched flaws on unpatched systems, not zero-days.
  • Public disclosure raises short-term risk by widening who can exploit it, which is the argument for having the fix ready first and patching fast.
  • Prevention at introduction (review, static analysis, memory-safe languages) is the cheapest intervention.

Test yourself

  1. List the stages of the vulnerability lifecycle.

Introduction of the flaw, discovery by some party, reporting to the vendor, triage and remediation, public disclosure with an advisory and identifier, availability of a patch, and adoption of that patch by each user.

  1. Why are "a patch is available" and "the window of exposure has closed" not the same event?

Because a fix protects only once installed. Between release and installation sit testing, change control and neglect, so each organisation's window closes when it patches; for devices nobody updates, it may never close.

  1. What is the zero-day period, and what defences apply during it?

The interval in which an attacker knows of the flaw and no fix exists, so defenders cannot patch. Only generic controls apply: network segmentation, least privilege, monitoring and detection, and any temporary workaround the vendor publishes.

  1. Why does independent discovery matter to disclosure policy?

Because a vendor who delays a fix is not only keeping one researcher waiting but gambling that no one else, including an attacker, finds the same flaw meanwhile. Independent discovery is common, which is the main argument against open-ended timelines.

  1. Why does public disclosure raise risk in the short term, and why is it still the right practice?

Because publishing details expands the set of people able to exploit the flaw, and exploitation attempts rise sharply in the following days. It remains right because without disclosure defenders cannot know they are exposed or act at all; the answer is to have the fix available first and to patch quickly.

Contents This chapter on its own page

munotes.in54

Chapter Twelve

Responsible Disclosure Against Full Disclosure, and the Vendor's Side

Syllabus topic Module 1, "Vulnerability Research and Disclosure Mechanisms: ... responsible disclosure"

In one line

Responsible (coordinated) disclosure means telling the vendor privately first and publishing only once a fix exists or a fair deadline has passed. Full disclosure means publishing at once. The first is the professional norm; the second is a last resort for vendors who will not act.

In examination wording: coordinated (responsible) disclosure is the practice of privately notifying the affected vendor of a vulnerability, agreeing a remediation timeline, and publishing details only after a fix is available or the agreed period expires; full disclosure is the immediate public release of details; ISO/IEC 29147 addresses how an organisation receives and handles disclosures and ISO/IEC 30111 how it processes them internally.

The dilemma, stated fairly

You have found a serious flaw in software that millions of people use. You now hold knowledge that can be used to harm them. What should you do? Every available answer has a real cost.

Publish immediately. Users are warned and can take their own protective measures, and the vendor is under maximum pressure to act. But you have also handed a working attack to everyone hostile, before any fix exists. People are harmed in the gap, and they are people who never had a chance to protect themselves.

Tell no one. Nobody is armed by you. But the flaw sits there unfixed, and somebody with worse intentions may find it independently, which the previous chapter showed is common. Your silence protects nobody in the long run.

Tell only the vendor and wait indefinitely. The ideal, if the vendor acts. But some vendors ignore reports for years when there is no pressure, and a few respond to reports with lawyers rather than patches. Waiting for ever means the users stay exposed and never learn.

Responsible disclosure is the compromise the field settled on, and its logic is now easy to state: tell the vendor privately so a fix can exist, but attach a deadline so that silence is not a permanent option. It balances the user's need for a warning against the user's need for a patch to exist first.

Coordinated disclosure, in practice

The sequence, and the norms around it:

  1. Find the security contact. A mature organisation publishes one: a security@ address, a security policy page, or a security.txt file. Where none exists, the finder may go through a national coordinating body (India's CERT-In) or a platform.
  2. Report privately, with enough detail to reproduce: affected versions, steps, impact, and often a suggested fix.
  3. Agree a timeline. A commonly used default among large coordinators is 90 days, with flexibility: extended if the vendor is working in good faith and needs more, shortened if the flaw is being actively exploited.
  4. Stay in contact. The finder answers questions; the vendor reports progress. Most breakdowns are caused by silence, not by disagreement.
  5. Publish after the fix, or after the deadline. Usually coordinated so the advisory, the CVE and the patch appear together.
  6. Credit the finder, which is both courteous and a practical incentive.
munotes.in55

Responsible Disclosure Against Full Disclosure, and the Vendor's Side

The key design feature is the fixed deadline. Without it, a vendor can neutralise a report by simply never responding, and the researcher has no lawful lever. With it, the vendor knows the clock is running and the researcher does not have to choose between waiting for ever and publishing recklessly.

Full disclosure, and when it is defensible

Full disclosure publishes everything at once, publicly. Its advocates make two arguments that deserve to be taken seriously rather than dismissed:

  • It forces action. Historically, some vendors ignored private reports and fixed the same flaws within days of public exposure. The pressure is real and sometimes it is the only thing that works.
  • It respects users' autonomy. Users are exposed whether or not they know. Telling them lets them decide, disable the feature, add a workaround, or switch products, rather than being kept ignorant for the vendor's convenience.

The objection is equally real: publication arms every attacker instantly, and the users least able to respond quickly are the ones harmed. Today the field treats full disclosure as a last resort, justified mainly where a vendor has ignored a good-faith coordinated report, or where the flaw is already being exploited and users need to defend themselves now.

A middle practice worth naming is partial disclosure: announcing that a flaw exists, with its severity and a workaround, while withholding the details that make exploitation easy. It warns without arming, though it is an unstable position, since researchers elsewhere often reconstruct the flaw from the hint.

Coordinated disclosureFull disclosure
Who is told firstThe vendor, privatelyEveryone, at once
Fix usually exists at publicationYesNo
Pressure on the vendorA deadlineImmediate and maximal
Risk to users before a fixLowHigh
Status in the fieldThe normLast resort

The vendor's side, which is half the practice

Disclosure is not only something researchers do to organisations. A vulnerability arriving at an unprepared organisation goes badly, and the international standards recognise this by splitting the subject in two: ISO/IEC 29147 covers vulnerability disclosure, how an organisation receives and responds to reports from outside, and ISO/IEC 30111 covers vulnerability handling, the internal process of investigating and fixing.

What a mature vendor does:

  • Publishes a way to be reached, and makes sure it reaches security people rather than a general support queue where reports are closed as "not a bug".
  • Acknowledges quickly, within a day or two. Silence is the single biggest cause of researchers going public.
  • Triages honestly, reproduces the issue, assesses severity and scope, and tells the finder what it concluded.
  • Keeps the finder informed of progress and of the intended release date.
  • Requests or assigns a CVE and issues an advisory naming affected versions and the fix.
  • Credits the finder, unless they prefer anonymity.
  • Does not threaten. Responding to a good-faith report with legal threats is the behaviour that pushes the entire field toward full disclosure, and it discourages the next finder from reporting at all.
munotes.in56

Responsible Disclosure Against Full Disclosure, and the Vendor's Side

The last point is worth dwelling on because it is the strategic argument. An organisation's choice is not between hearing about flaws and not having them. It is between hearing about them from a researcher or from an attacker. Everything above is designed to make the first more likely.

Where this leaves the ethical hacker

Two boundaries a student must not blur.

Disclosure policy does not confer permission to test. Coordinated disclosure governs what you do with a flaw you found lawfully. It says nothing about whether you were entitled to look. Finding a flaw in a stranger's system without authorisation is unauthorised access under section 43, and intending to report it is not a defence. The lawful route to finding flaws in someone else's systems is a bug bounty or a written scope.

Within an engagement, disclosure is to the client, not the world. A penetration tester's findings belong to the client under contract. Publishing them, even after the engagement, requires the client's agreement; writing them up as a case study without permission breaches confidentiality and, where personal data is involved, engages section 72A.

A worked example

A student finds, in a widely used open-source library, that a particular input causes it to return data from memory it should not.

Step 1. She checks how she found it. She was testing the library on her own machine, in her own project. That is lawful: it is her own system. Had she found it by probing a stranger's live service, she would have a legal problem before any disclosure question arose.

Step 2. She looks for a security contact and finds a security@ address and a published policy promising acknowledgement in three working days.

Step 3. She reports privately: affected versions, a minimal reproduction, the impact (memory disclosure, potentially including secrets), and her assessment that it is high severity. She does not publish anything.

Step 4. The maintainers acknowledge in two days, confirm it, and say a fix will take six weeks because three supported branches are affected and downstream distributors need lead time. She agrees, and they settle a coordinated publication date.

munotes.in57

Responsible Disclosure Against Full Disclosure, and the Vendor's Side

Step 5. On the agreed date the fix, the advisory and the CVE appear together, crediting her. She then publishes her own write-up, which is now safe because users can already protect themselves.

The variation that changes the answer. If, at step 4, the maintainers had never replied, she would have followed up, then notified a coordinating body, and at the end of her stated deadline published a limited advisory: enough for users to protect themselves, withholding the most directly weaponisable detail. That is the last-resort position, and it is defensible precisely because she exhausted the coordinated route first.

What beginners get wrong

  • Thinking responsible disclosure means "tell everyone eventually". It means tell the vendor first and publish only after a fix or a fair deadline.
  • Believing a disclosure policy legalises testing. It governs what you do with a flaw, not whether you were permitted to look for it. Authorisation is a separate question with a separate answer.
  • Publishing a proof of concept immediately "to help defenders". Before a fix exists, a working exploit helps attackers far more, because defenders cannot patch what has no patch.
  • Going public at the first silence. Follow up, escalate to a coordinating body, and give a stated deadline. Publishing in irritation is not full disclosure on principle.
  • Treating the vendor as the adversary. Most delays are ordinary engineering and coordination. The adversarial posture is reserved for vendors who ignore or threaten.
  • Writing up client findings publicly. Engagement findings are confidential and belong to the client; publishing needs their agreement.

Quick revision

  • The dilemma: publishing at once arms attackers before a fix; saying nothing leaves users exposed; telling only the vendor can mean waiting for ever.
  • Coordinated (responsible) disclosure: private report, agreed timeline (90 days is a common default, flexible both ways), publish after the fix or the deadline, credit the finder.
  • The fixed deadline is the design feature that stops a vendor burying a report by never replying.
  • Full disclosure: immediate publication; a last resort, defensible where a vendor has ignored a good-faith report or the flaw is already being exploited. Partial disclosure warns without arming.
  • The vendor's half: ISO/IEC 29147 (receiving and disclosing) and ISO/IEC 30111 (internal handling). Publish a contact, acknowledge fast, triage honestly, keep the finder informed, issue an advisory and a CVE, credit, and never threaten.
  • Disclosure policy is not permission to test; engagement findings belong to the client.

Test yourself

  1. What problem does coordinated disclosure solve, and what is the role of the deadline?

It balances warning users against arming attackers: the vendor is told privately so a fix can exist before details are public. The deadline prevents a vendor neutralising the report by never responding, so that silence is not a permanent option.

munotes.in58

Responsible Disclosure Against Full Disclosure, and the Vendor's Side

  1. When is full disclosure defensible?

As a last resort: principally where the vendor has ignored or refused to act on a good-faith coordinated report, or where the flaw is already being actively exploited and users need information to defend themselves immediately.

  1. What do ISO/IEC 29147 and ISO/IEC 30111 each address?

29147 addresses vulnerability disclosure, how an organisation receives reports from outside and communicates about them; 30111 addresses vulnerability handling, the internal process of investigating, remediating and coordinating the fix.

  1. Why is responding to a good-faith report with legal threats strategically self-defeating?

Because the organisation's real choice is whether it hears about flaws from researchers or from attackers. Threats discourage future reports, push the field toward full disclosure, and leave the organisation learning about its vulnerabilities only when they are exploited.

  1. A researcher finds a flaw by probing a company's live website uninvited and then reports it responsibly. Does responsible disclosure make their conduct lawful?

No. Disclosure practice governs what is done with a flaw already found; it does not authorise the access. Probing without permission engages section 43 regardless of the intention to report. The lawful route is a bug bounty or a written scope.

Contents This chapter on its own page

munotes.in59

Chapter Thirteen

CVE and CWE: Naming the Flaw and Naming the Weakness

Syllabus topic Module 1, "Vulnerability Research and Disclosure Mechanisms: ... CVE identification"

In one line

A CVE is a unique name for one vulnerability in one product, so that everybody means the same thing. A CWE is a name for the kind of weakness that caused it, so that an organisation can fix the pattern rather than the instance.

In examination wording: Common Vulnerabilities and Exposures (CVE) is a catalogue that assigns a unique identifier to each publicly disclosed vulnerability, enabling unambiguous reference across tools, advisories and databases; Common Weakness Enumeration (CWE) is a hierarchical classification of the underlying types of software and hardware weakness; a CVE record identifies an instance, and it is typically mapped to the CWE describing its class.

Why naming had to be solved before anything else

Before CVE, the same flaw had as many names as there were companies talking about it. One scanner called it one thing, a vendor advisory another, a news article a third, and nobody could reliably tell whether two reports described the same problem or two different ones. An organisation could not answer the basic question "have we already fixed this?", and tools could not be compared, because each vendor's list was written in its own vocabulary.

CVE solved a coordination problem, not a technical one. It gives every publicly known vulnerability one identifier that everyone uses, so a scanner's output, a vendor's advisory, a news report and a patch note can all be matched against each other automatically. That sounds mundane and it is the foundation on which vulnerability management is built.

CVE: the identifier

A CVE identifier has the form CVE-YEAR-NUMBER, for example CVE-2014-0160 or CVE-2021-44228. The year is the year the identifier was reserved, not necessarily the year of disclosure, so a CVE-2025 identifier may be published in 2026.

Who assigns them. Identifiers are issued by CVE Numbering Authorities (CNAs). The programme is coordinated by the MITRE Corporation as the primary authority, and many large vendors and open-source projects are CNAs for their own products, which lets them assign identifiers themselves as part of their advisory process. A researcher reporting to a vendor that is a CNA will usually receive a CVE from that vendor.

What a CVE record contains. A brief description, the affected product and versions, and references to advisories and patches. It is deliberately minimal.

What a CVE is not, and this is the examinable part:

  • It is not a severity. CVE-2021-44228 tells you which flaw; it says nothing about how bad it is. Severity is CVSS, the next chapter.
  • It is not a vulnerability database. The identifier is a name; the detail lives in databases that reference it.
  • It is not a guarantee of exploitability. Many CVEs are never exploited in practice.
  • It is not exhaustive. Flaws fixed silently, or found and never reported, have no CVE. An absence of CVEs is not evidence of security; it may mean nobody is looking, which is why a product with many CVEs is sometimes the better-scrutinised one.
munotes.in60

CVE and CWE: Naming the Flaw and Naming the Weakness

CWE: the class of weakness

A CVE is an instance. CWE names the type of mistake behind it. Where CVE says "this flaw, in this product", CWE says "this is an SQL injection", or "this is an out-of-bounds write".

Examples a student should recognise:

CWEWeaknessWhere this book teaches it
CWE-79Improper neutralisation of input during web page generation (cross-site scripting)the XSS chapters
CWE-89Improper neutralisation of special elements used in an SQL command (SQL injection)the SQL injection chapters
CWE-787Out-of-bounds writethe buffer overflow chapters
CWE-22Improper limitation of a pathname (path traversal)web server hardening
CWE-352Cross-site request forgerythe session block
CWE-798Use of hard-coded credentialscryptographic weaknesses

CWE is hierarchical: broad classes contain narrower ones, so a specific weakness can be described at the level of detail that suits the purpose. That structure is what makes it useful for measurement, because you can count at a chosen level.

Why the distinction earns its keep. Suppose a company fixes twelve CVEs in a quarter. Counting CVEs tells them they fixed twelve bugs. Mapping them to CWEs might reveal that nine were CWE-89, SQL injection. That is a different and far more actionable fact: the problem is not twelve bugs, it is one practice, queries built by string concatenation. The fix is not twelve patches but a coding standard, a library, and a check in the build pipeline. CVE counts work; CWE reveals causes.

This is also why OWASP categories (a later chapter) map to CWEs: they are both talking about classes of weakness rather than instances.

The databases and the machinery

MU's topic speaks of vulnerability research, and the identifiers only matter because of what consumes them.

The National Vulnerability Database (NVD), run by the United States' NIST, takes CVE records and enriches them: it adds CVSS severity scores, CWE mappings, and structured data about affected configurations. In practice most tools read NVD rather than the bare CVE list, because the bare list has no severity.

Vendor advisories are the authoritative statement about a vendor's own products: which versions are affected, what the fix is, and any workaround. When a vendor advisory and a third-party description disagree, the vendor's is usually the one to act on.

Exploit and threat intelligence sources answer a different question: not "does this flaw exist?" but "is anyone actually using it?". A catalogue of vulnerabilities known to be exploited in the wild is more useful for prioritisation than severity alone, because a medium-severity flaw under active attack deserves attention before a critical one nobody has ever exploited.

munotes.in61

CVE and CWE: Naming the Flaw and Naming the Weakness

Vulnerability scanners are the tools that tie it together. A scanner identifies the software and version running on a host (the enumeration of a later chapter), looks up which CVEs affect that version, and reports them with severity. Understanding that pipeline explains both the value and the limits of scanners:

  • They find known flaws in identified software. They cannot find a flaw that has no CVE, and they cannot find anything in software they failed to identify.
  • They infer from version numbers, so they produce false positives when a fix has been back-ported without changing the version string, which is common on Linux distributions, and false negatives when a banner is suppressed or wrong.
  • They do not prove exploitability. That is the distinction between a vulnerability assessment and a penetration test from the earlier chapter.

A worked example

A scanner reports on a web server: CVE-2021-44228, CVSS 10.0, Apache Log4j 2.14.1.

Read it properly, piece by piece:

  • CVE-2021-44228 is the name. It lets the team match this against the vendor advisory, the news coverage and the patch note, and confirm they are all the same issue.
  • CVSS 10.0 is the severity, from NVD, and it is intrinsic, not the organisation's risk.
  • Log4j 2.14.1 is the affected component and version, which tells them what to change.
  • The CWE mapping (improper input neutralisation leading to injection) tells them the class, which prompts the wider question: where else do we evaluate untrusted input in a context that can execute?

The team then asks the questions the identifiers alone do not answer: is this server internet-facing, does it process untrusted input, is the flaw known to be exploited in the wild (it was, extensively), and do we have a temporary mitigation while we patch? That combination of identifier, severity, exposure and exploitation status is what real prioritisation uses.

What beginners get wrong

  • Treating a CVE as a severity. It is a name. Severity is CVSS, and risk is severity plus context.
  • Confusing CVE with CWE. CVE identifies one flaw in one product; CWE identifies the class of mistake. "CWE-89" is not a vulnerability, it is a kind of vulnerability.
  • Reading "no CVEs" as "secure". It may mean the product is unexamined, or that the vendor fixes silently without requesting identifiers.
  • Trusting a scanner's version inference absolutely. Back-ported fixes cause false positives; suppressed or wrong banners cause false negatives. A finding is a hypothesis until confirmed.
  • Prioritising by CVSS alone. Exposure and whether the flaw is actually being exploited matter at least as much.
  • Assuming the CVE year is the disclosure year. It is the year the identifier was reserved.
munotes.in62

CVE and CWE: Naming the Flaw and Naming the Weakness

Quick revision

  • CVE-YEAR-NUMBER uniquely names one vulnerability in one product, assigned by a CNA, coordinated by MITRE. It is a name, not a severity, not a database, and not proof of exploitability.
  • CWE names the class of weakness and is hierarchical: CWE-79 cross-site scripting, CWE-89 SQL injection, CWE-787 out-of-bounds write, CWE-22 path traversal, CWE-352 CSRF, CWE-798 hard-coded credentials.
  • CVE counts work done; CWE reveals the underlying practice to fix. Nine CVEs mapping to CWE-89 means one bad habit, not nine bugs.
  • NVD enriches CVE records with CVSS scores and CWE mappings; vendor advisories are authoritative for their own products; exploited-in-the-wild catalogues answer whether anyone is actually using it.
  • Scanners match identified versions to known CVEs: they miss what has no CVE or was not identified, produce false positives on back-ported fixes, and do not prove exploitability.

Test yourself

  1. What is the difference between a CVE and a CWE?

A CVE uniquely identifies one specific vulnerability in one product, so that everyone refers to the same flaw. A CWE identifies the class or type of weakness that underlies it, such as SQL injection or out-of-bounds write. One names an instance; the other names the category.

  1. Why is mapping findings to CWEs more useful than counting CVEs?

Because CVE counts measure work done while CWE mappings reveal the cause: several CVEs sharing one CWE show a single faulty practice, which can be fixed once through a standard, a library or a pipeline check, rather than patched repeatedly.

  1. Why is "this product has no CVEs" weak evidence of security?

Because a lack of identifiers may mean the product is little examined, or that its vendor fixes issues silently without requesting CVEs. A well-scrutinised product may have many CVEs precisely because people are looking at it.

  1. How does a vulnerability scanner reach its conclusions, and what are the two characteristic errors?

It identifies the software and version on a host and looks up which CVEs affect that version. It produces false positives when a fix has been back-ported without changing the version string, and false negatives when the version banner is suppressed, altered or misread. It also does not prove exploitability.

  1. What does a CVSS score of 10.0 on a CVE tell you, and what does it not?

It tells you the flaw's intrinsic severity is maximal: remotely reachable, easy, requiring no privileges or interaction, with total impact and scope changed. It does not tell you your risk, which depends on whether you run the software, how exposed it is, and whether the flaw is being exploited in the wild.

Contents This chapter on its own page

munotes.in63

Chapter Fourteen

CVSS: the Eight Base Metrics

Syllabus topic Module 1, "Vulnerability Research and Disclosure Mechanisms: ... CVSS scoring"

In one line

CVSS turns a vulnerability's characteristics into a number from 0.0 to 10.0, using eight base metrics: four about how hard it is to exploit and four about how bad it is if exploited.

In examination wording: the Common Vulnerability Scoring System is an open standard for communicating the characteristics and severity of a vulnerability. Its Base metric group captures the intrinsic qualities of a vulnerability that are constant over time and across environments, and comprises the Exploitability metrics (Attack Vector, Attack Complexity, Privileges Required, User Interaction), the Scope metric, and the Impact metrics (Confidentiality, Integrity, Availability).

Why a score was needed

A security team with three hundred open findings cannot fix them all at once and must decide what to do first. Left to words, this goes badly: "critical" means different things to different people, every vendor grades its own flaws generously, and two teams reading the same advisory reach different conclusions.

CVSS replaces the adjective with a reproducible calculation. Two analysts given the same facts about a vulnerability should produce the same number, and if they disagree, the disagreement is localised to a specific metric where it can be argued out. That reproducibility is the whole value, and it is why the score is always published with its vector string, the compact record of the choices made, so anyone can check the reasoning rather than just accepting the number.

The version taught here is v3.1, the one under which almost every CVE in circulation is scored. Version 4.0 exists and refines the model; v3.1 remains what a student will meet in advisories, scanners and examinations.

The vector string

A CVSS score is always accompanied by something like:

CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N

Each pair is a metric and its value. Learn to read it and you can reconstruct the whole assessment: this one is Network, Low complexity, no Privileges, no User interaction, Scope Unchanged, Confidentiality High, Integrity None, Availability None. The number is derived; the vector is the evidence.

The Exploitability metrics: how hard is it?

Attack Vector (AV): how close must the attacker be?

ValueMeaningWeight
Network (N)Exploitable across a network, potentially from the internet0.85
Adjacent (A)Requires being on the same local or logical network0.62
Local (L)Requires local access to the machine, such as a shell or a logged-in session0.55
Physical (P)Requires physically touching the device0.20

The question is reach. Network is worst because the population of possible attackers is the whole internet; Physical is least severe because the attacker must be present. Note that Local includes an attacker who already has a foothold, which is why local privilege-escalation flaws still matter.

munotes.in64

CVSS: the Eight Base Metrics

Attack Complexity (AC): does it work reliably?

ValueMeaningWeight
Low (L)Works repeatably, no special conditions0.77
High (H)Requires conditions beyond the attacker's control, such as winning a race or knowing a secret0.44

The question is reliability. High complexity means the attacker must succeed at something they cannot simply arrange, which genuinely reduces the practical threat. It does not mean "technically difficult": a sophisticated exploit that works every time is Low.

Privileges Required (PR): what must the attacker already have?

ValueMeaningWeight (Scope Unchanged)Weight (Scope Changed)
None (N)No authentication at all0.850.85
Low (L)Ordinary user privileges0.620.68
High (H)Administrative privileges0.270.50

The question is what the attacker must start with. Requiring no privileges is worst. Note the curiosity that the Low and High weights are higher when Scope is Changed, because escaping the security boundary from a limited position is a more serious achievement.

User Interaction (UI): must a victim do something?

ValueMeaningWeight
None (N)The attacker acts alone0.85
Required (R)A user must take an action, such as opening a file or clicking a link0.62

The question is whether the attack is self-contained. Requiring interaction lowers the score because it adds a dependency the attacker cannot guarantee, though in practice users do click, which is why phishing works and why this metric is sometimes argued to be generous to the defender.

Scope (S): does the damage stay in the box?

ValueMeaning
Unchanged (U)The impact is confined to the vulnerable component's own security authority
Changed (C)The impact reaches components beyond it

Scope is the metric students find hardest and it is the one that most often moves a score from High to Critical, so it repays attention.

The idea is a security authority: the thing that decides what a component may do. Scope is Changed when exploiting the vulnerable component lets the attacker affect resources governed by a different authority. The classic example is a virtual machine escape, where a flaw in the hypervisor's guest handling lets a guest affect the host or other guests: the attack began in one security authority and its effects landed in another.

Another common case is a vulnerable component that acts on the attacker's behalf against other systems, such as a flaw in a web application that causes the server to make requests to internal services. The application was the vulnerable component; the internal service belongs to a different authority.

Scope Changed both raises the Impact calculation and multiplies the final result, so it is worth getting right.

The Impact metrics: how bad if it works?

Confidentiality (C), Integrity (I) and Availability (A) are scored separately, and they are the CIA triad from the earlier chapter used as a measuring instrument.

munotes.in65

CVSS: the Eight Base Metrics

ValueMeaningWeight
High (H)Total loss, or serious loss of the most important information0.56
Low (L)Some loss, limited in extent or the attacker cannot control what is affected0.22
None (N)No impact on that property0.00

Two points that examiners probe:

They are scored independently. A flaw that leaks data without altering anything is C:H/I:N/A:N. A flaw that crashes a service without revealing anything is C:N/I:N/A:H. A full system compromise is C:H/I:H/A:H.

If all three are None, the score is zero, regardless of how easy the flaw is to reach. A defect that affects nothing is not a vulnerability. This is the sanity check built into the model, and it is why "trivially exploitable" does not by itself mean "severe".

The severity bands

ScoreRating
0.0None
0.1 to 3.9Low
4.0 to 6.9Medium
7.0 to 8.9High
9.0 to 10.0Critical

A worked reading of two vectors

AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N (this is Heartbleed's). Reachable over the network, works reliably, needs no privileges and no user action: the exploitability half is as bad as it gets. But the impact half is limited to confidentiality; it reads memory and alters nothing, destroys nothing. Scope Unchanged. The result is 7.5, High. The lesson: maximal exploitability with partial impact gives a High, not a Critical.

AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H (this is Log4Shell's shape). The same maximal exploitability, but now every impact metric is High and Scope is Changed. The result is 10.0, Critical. The lesson: Scope plus total impact is what reaches the maximum.

Comparing the two vectors side by side is the most efficient way to understand the model, because only the impact half and Scope differ, and the score moves from 7.5 to 10.0.

What beginners get wrong

  • Reading Attack Complexity as "technically difficult". It means the attacker depends on conditions outside their control. A sophisticated but reliable exploit is Low complexity.
  • Confusing Privileges Required with User Interaction. The first is what the attacker must already have; the second is what a victim must do.
  • Ignoring Scope. It is the metric that most often separates High from Critical, and it asks whether the impact escapes the vulnerable component's security authority.
  • Assuming easy means severe. If all three impact metrics are None the score is 0.0 however trivial the flaw is to trigger.
  • Treating the base score as the organisation's risk. It is intrinsic and deliberately context-free; risk adds exposure and business impact, which is the next chapter.
  • Quoting the number without the vector. The vector is the reasoning; without it the score cannot be checked or argued.

Quick revision

  • CVSS v3.1 Base gives 0.0 to 10.0 from eight metrics, always published with a vector string that records the reasoning.
  • Exploitability: Attack Vector (Network, Adjacent, Local, Physical: how close), Attack Complexity (Low, High: reliability, not difficulty), Privileges Required (None, Low, High: what the attacker starts with), User Interaction (None, Required: must a victim act).
  • Scope (Unchanged, Changed): does the impact escape the vulnerable component's security authority? Changed raises impact and multiplies the result.
  • Impact: Confidentiality, Integrity, Availability, each High, Low or None, scored independently. All three None gives a score of 0.0.
  • Bands: None 0.0; Low 0.1 to 3.9; Medium 4.0 to 6.9; High 7.0 to 8.9; Critical 9.0 to 10.0.
munotes.in66

CVSS: the Eight Base Metrics

Test yourself

  1. Name the eight base metrics and say which group each belongs to.

Exploitability: Attack Vector, Attack Complexity, Privileges Required, User Interaction. Impact: Confidentiality, Integrity, Availability. Scope sits between them, describing whether the impact escapes the vulnerable component's security authority.

  1. What does Attack Complexity actually measure, and why is "this exploit is very sophisticated" not the test?

It measures whether exploitation depends on conditions beyond the attacker's control, such as winning a race condition or already knowing a secret. A highly sophisticated exploit that works reliably every time is Low complexity, because nothing outside the attacker's control has to go right.

  1. Explain Scope, and give an example of Scope Changed.

Scope records whether exploiting the vulnerable component affects resources governed by a different security authority. A virtual machine escape is the classic example: the flaw is in the hypervisor's handling of a guest, and the impact lands on the host or on other guests, which belong to a different authority.

  1. Why can a trivially exploitable flaw score 0.0?

Because if Confidentiality, Integrity and Availability impacts are all None, the flaw affects nothing, and the model returns zero regardless of how reachable or reliable it is. Exploitability without impact is not a vulnerability.

  1. Heartbleed scores 7.5 and Log4Shell 10.0 although both are network-reachable, reliable, and need no privileges or interaction. What accounts for the difference?

The impact half and Scope. Heartbleed affects confidentiality only, with integrity and availability None and Scope Unchanged; Log4Shell has all three impacts High and Scope Changed, which both raises the impact calculation and multiplies the final score.

Contents This chapter on its own page

munotes.in67

Chapter Fifteen

CVSS: Working a Score, and the Temporal and Environmental Metrics

Syllabus topic Module 1, "Vulnerability Research and Disclosure Mechanisms: ... CVSS scoring"

In one line

The base score is built in three steps: combine the three impact metrics into a sub-score, combine the four exploitability metrics into another, add them and round up. Then Temporal and Environmental metrics adjust the result for what is true today and for your particular network.

In examination wording: the CVSS base score is computed from an Impact sub-score derived from the Confidentiality, Integrity and Availability metrics and an Exploitability sub-score derived from Attack Vector, Attack Complexity, Privileges Required and User Interaction, combined according to the Scope metric and rounded up to one decimal place; the optional Temporal metric group adjusts for the current state of exploit and remediation availability, and the Environmental group for the importance and configuration of the asset in a specific organisation.

The formulas

Four steps, and you should understand the shape rather than memorise the constants.

Step 1: the Impact Sub-Score (ISS). Combine the three impact metrics:

ISS = 1 - [(1 - C) x (1 - I) x (1 - A)]

The form is worth understanding. Each term (1 - X) is "how much of that property survives". Multiply them to get how much survives overall, and subtract from 1 to get how much was lost. The consequence is that the metrics compound but saturate: going from one High impact to three does raise the score, but not threefold, because each additional loss matters less once something is already fully lost.

Step 2: Impact. Scale the sub-score, and here Scope matters:

  • Scope Unchanged: Impact = 6.42 x ISS
  • Scope Changed: Impact = 7.52 x (ISS - 0.029) - 3.25 x (ISS - 0.02)^15

The Changed formula is a curve rather than a straight line, which is why it cannot be worked comfortably by hand and why a calculator is the right tool.

Step 3: Exploitability. Multiply the four exploitability weights:

Exploitability = 8.22 x AV x AC x PR x UI

Step 4: the Base Score.

  • If Impact is zero or less, the score is 0.0.
  • Scope Unchanged: Roundup( minimum( Impact + Exploitability, 10 ) )
  • Scope Changed: Roundup( minimum( 1.08 x (Impact + Exploitability), 10 ) )

Roundup means round up to one decimal place: the smallest one-decimal number that is at least the input. It is always up, never to nearest, so 7.482 becomes 7.5 and 7.401 also becomes 7.5.

Working Heartbleed by hand

Take AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N.

The impact half. Confidentiality is High (0.56); Integrity and Availability are None (0). So ISS = 1 - (1 - 0.56)(1 - 0)(1 - 0) = 1 - 0.44 = 0.56. Scope is Unchanged, so Impact = 6.42 × 0.56 = 3.5952.

The exploitability half. Multiplying the four weights, 8.22 by 0.85 (Attack Vector Network) by 0.77 (Attack Complexity Low) by 0.85 (Privileges Required None) by 0.85 (User Interaction None), gives about 3.887.

munotes.in68

CVSS: Working a Score, and the Temporal and Environmental Metrics

The result. Adding, 3.5952 plus about 3.887 is about 7.482, and the roundup gives 7.5, which is High. That matches the published score in the National Vulnerability Database, which is the check that the method was applied correctly.

Notice which half limited the result. The exploitability half was as large as it can be; the impact half was held down because two of the three impact metrics are None. Heartbleed reads memory and alters nothing, and that is the whole reason it is 7.5 rather than 10.

Working it by program

The same computation as a small program. It is safe and self-contained: arithmetic on a vector string, attacking nothing.

import math

AV = {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.20}
AC = {"L": 0.77, "H": 0.44}
UI = {"N": 0.85, "R": 0.62}
CIA = {"H": 0.56, "L": 0.22, "N": 0.00}
PR_UNCHANGED = {"N": 0.85, "L": 0.62, "H": 0.27}
PR_CHANGED = {"N": 0.85, "L": 0.68, "H": 0.50}


def roundup(value):
    # The specification's Roundup: the smallest one-decimal number >= value.
    scaled = round(value * 100000)
    if scaled % 10000 == 0:
        return scaled / 100000.0
    return (math.floor(scaled / 10000) + 1) / 10.0


def base_score(av, ac, pr, ui, scope, c, i, a):
    changed = scope == "C"
    pr_weight = (PR_CHANGED if changed else PR_UNCHANGED)[pr]
    exploitability = 8.22 * AV[av] * AC[ac] * pr_weight * UI[ui]
    iss = 1 - (1 - CIA[c]) * (1 - CIA[i]) * (1 - CIA[a])
    if changed:
        impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15
    else:
        impact = 6.42 * iss
    if impact <= 0:
        return 0.0
    combined = impact + exploitability
    if changed:
        combined = 1.08 * combined
    return roundup(min(combined, 10))


def score_vector(vector):
    fields = dict(pair.split(":") for pair in vector.split("/")
                  if ":" in pair and not pair.startswith("CVSS"))
    return base_score(fields["AV"], fields["AC"], fields["PR"],
                      fields["UI"], fields["S"], fields["C"],
                      fields["I"], fields["A"])


examples = [
    ("AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", "Heartbleed: reads memory only"),
    ("AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H", "Log4Shell shape: total, scope changed"),
    ("AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "local privilege escalation"),
    ("AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N", "stored-XSS shape: needs a click"),
    ("AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N", "reachable but affects nothing"),
]
for vector, description in examples:
    print(f"{score_vector(vector):>5}  {vector}  ({description})")
  7.5  AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N  (Heartbleed: reads memory only)
 10.0  AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H  (Log4Shell shape: total, scope changed)
  7.8  AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H  (local privilege escalation)
  4.2  AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N  (stored-XSS shape: needs a click)
  0.0  AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:N  (reachable but affects nothing)

Read the five lines as a set, because together they teach the model better than any single one.

  • 7.5 reproduces the hand calculation and the published figure.
  • 10.0 shows what reaches the maximum: total impact plus Scope Changed.
  • 7.8 is instructive: the impact is total, exactly as in the 10.0 case, yet the score is lower, because Attack Vector is Local. Reach matters as much as damage.
  • 4.2 shows the cost of dependencies: High complexity and a required user action pull a genuine flaw down into Medium.
  • 0.0 is the sanity check from the previous chapter, demonstrated: a flaw that is network-reachable, reliable and needs nothing at all scores zero when it affects none of the three properties.
munotes.in69

CVSS: Working a Score, and the Temporal and Environmental Metrics

Temporal metrics: what is true today

The base score is deliberately frozen; it describes the flaw itself and never changes. But the practical danger does change, and the Temporal group captures that. It can only ever lower the score from the base, never raise it.

  • Exploit Code Maturity. Is there a working exploit? The range runs from Unproven, through Proof-of-Concept and Functional, to High (reliable, widely available, or automated in tooling). A flaw with public reliable exploit code is a different practical problem from one nobody has weaponised.
  • Remediation Level. Is there a fix? From Unavailable, through Workaround and Temporary Fix, to Official Fix. A flaw with an official patch is less dangerous in practice, because you can act.
  • Report Confidence. How sure are we that this is real and correctly described? From Unknown, through Reasonable, to Confirmed.

The useful insight is that Temporal metrics move in opposite directions over time: as a flaw ages, exploit code tends to mature (raising practical danger) while remediation becomes available (lowering it). Which dominates is exactly the question a triage meeting is arguing about.

Environmental metrics: what is true for you

The Environmental group re-scores the flaw for a specific organisation, and this is where "severity" finally becomes "risk".

  • Security Requirements (CR, IR, AR). How much do Confidentiality, Integrity and Availability matter for this asset? Each can be Low, Medium or High. A public marketing site may have Low confidentiality requirement and High availability requirement; a payroll database the reverse. These reweight the impact metrics.
  • Modified Base Metrics. Any base metric can be overridden to reflect your deployment. If a flaw is scored Attack Vector Network but in your network the service is reachable only from an internal segment, you set Modified Attack Vector to Adjacent or Local and the score falls accordingly. If you have already applied a compensating control that requires authentication in front of it, Modified Privileges Required rises.

This is the formal answer to the complaint that "CVSS does not know my network". It can, if you supply the information, and mature vulnerability-management programmes do exactly this rather than working from base scores alone.

Prioritising properly

Putting the chapter together, a sound priority order uses three inputs, not one:

  1. Base severity, the intrinsic score.
  2. Exposure, from the Environmental group: is the affected thing internet-facing, does it hold important data, is it reachable by untrusted users?
  3. Exploitation status, from the Temporal group and from threat intelligence: is this being exploited in the wild right now?
munotes.in70

CVSS: Working a Score, and the Temporal and Environmental Metrics

The third is the one teams most often omit and the one that most improves decisions. A Medium-severity flaw under active mass exploitation on an internet-facing server outranks a Critical flaw on an isolated internal system that nobody has ever exploited. A scanner sorting purely by base score will get that ordering exactly backwards.

What beginners get wrong

  • Treating the base score as risk. It is intrinsic and context-free by design. Risk needs exposure and exploitation status, which the Environmental and Temporal groups supply.
  • Expecting Temporal metrics to raise the score. They only lower it from the base.
  • Rounding intermediate values and then adding. CVSS keeps full precision until the final roundup; rounding early gives a slightly wrong answer.
  • Forgetting that Roundup is always upward. It is not round-to-nearest, so 7.401 becomes 7.5.
  • Ignoring Scope in the final step. Scope Changed both alters the Impact formula and multiplies the combined value by 1.08.
  • Patching strictly in base-score order. Exposure and active exploitation routinely reorder the list, and ignoring them wastes effort on flaws nobody is using.

Quick revision

  • ISS = 1 - (1 - C)(1 - I)(1 - A); impacts compound but saturate.
  • Impact = 6.42 x ISS (Scope Unchanged) or a curve (Scope Changed). Exploitability = 8.22 x AV x AC x PR x UI.
  • Base = Roundup(min(Impact + Exploitability, 10)), with the sum first multiplied by 1.08 if Scope is Changed. Impact of zero gives 0.0. Roundup is always upward, to one decimal.
  • Heartbleed works out to 7.5; total impact with Scope Changed reaches 10.0; the same total impact with Attack Vector Local gives 7.8.
  • Temporal (Exploit Code Maturity, Remediation Level, Report Confidence) adjusts for what is true today and can only lower the score.
  • Environmental (Security Requirements CR/IR/AR, and Modified Base Metrics) re-scores for your deployment, and is how severity becomes risk.
  • Prioritise on three inputs: base severity, exposure, and whether it is being exploited in the wild.

Test yourself

  1. State the four steps of the base-score calculation.

Compute the Impact Sub-Score from the three impact metrics as 1 minus the product of their survivals; scale it into Impact according to Scope; compute Exploitability as 8.22 times the four exploitability weights; add Impact and Exploitability, multiply by 1.08 if Scope is Changed, cap at 10 and round up to one decimal.

  1. Two flaws both have Confidentiality, Integrity and Availability all High, but one scores 10.0 and the other 7.8. What explains the difference?

The exploitability half. The 10.0 case is network-reachable with Scope Changed; the 7.8 case has Attack Vector Local, so despite identical total impact the attacker must already be on the machine, and no Scope multiplier applies.

munotes.in71

CVSS: Working a Score, and the Temporal and Environmental Metrics

  1. What do the Temporal metrics capture, and can they increase the base score?

Exploit Code Maturity, Remediation Level and Report Confidence, which describe the current state of the flaw in the world rather than the flaw itself. They can only lower the score relative to the base, never raise it.

  1. How do the Environmental metrics turn severity into risk?

By letting an organisation state how much Confidentiality, Integrity and Availability matter for the specific asset (the Security Requirements) and by overriding any base metric to match the actual deployment, for example reducing Attack Vector from Network to Local where the service is only internally reachable.

  1. Why can a Medium-severity flaw legitimately be patched before a Critical one?

Because prioritisation combines base severity with exposure and exploitation status. A Medium flaw on an internet-facing system that is being actively exploited presents more real risk than a Critical flaw on an isolated internal system with no known exploitation.

Contents This chapter on its own page

munotes.in72

Chapter Sixteen

Bug Bounty Programmes

Syllabus topic Module 1, "Vulnerability Research and Disclosure Mechanisms: ... bug bounty frameworks"

In one line

A bug bounty programme is a company's standing, public invitation for outside researchers to find and report security flaws in named systems, under published rules, in exchange for recognition or payment. It is permission granted in advance, which is what makes the testing lawful.

In examination wording: a bug bounty is a crowdsourced vulnerability-discovery programme in which an organisation authorises independent researchers to test defined targets within a published scope and rules of engagement, and rewards valid, responsibly disclosed findings; by granting permission in advance it converts testing that would otherwise be unauthorised access into lawful, contracted activity.

Why a bug bounty exists

An organisation cannot hire enough testers to match the number of capable people, worldwide, who might look at its systems. A bounty turns that crowd from a pure threat into partly a resource: instead of someone finding a flaw and selling or using it, they find it and report it to you for a reward.

But the reason it works is not generosity. It solves two specific problems this module has already set up.

The legal problem. Without a bounty, a researcher who tests your site is "without permission of the owner" under section 43, whatever their motive. That is not a theoretical bar; it is why well-intentioned researchers have been threatened with prosecution for reporting flaws. A bounty is a standing, public grant of permission to anyone who accepts its rules, which removes the obstacle at its root.

The disclosure problem. A bounty's rules require private reporting and forbid publication until the organisation agrees. So the finding reaches the vendor first by design, and the coordinated-disclosure process of the previous chapter is built into the arrangement rather than depending on the finder's goodwill.

There is a third, commercial reason: a bounty is paid per valid finding, so an organisation pays for results rather than for time. It is a complement to a penetration test, not a substitute, because a bounty gives breadth and continuity while a test gives structured, guaranteed coverage within a scope and a deadline.

What a programme publishes

Every serious programme publishes the same parts, and they map exactly onto the three documents from the authorisation chapter.

Scope. The systems, domains and applications that may be tested, and explicitly those that may not. This is the legal boundary: anything outside it is unauthorised and falls back under section 43. Scopes commonly exclude third-party services the organisation does not own, recently acquired subsidiaries, and staging environments.

Rules of engagement. What techniques are permitted. Almost universally forbidden: denial-of-service and load testing, social engineering of staff or customers, physical intrusion, automated scanning that generates heavy traffic, and any access to real user data. Researchers are usually required to use their own test accounts and to stop as soon as a flaw is confirmed rather than exploring further.

munotes.in73

Bug Bounty Programmes

Reward structure. What a valid finding pays, banded by severity, often using CVSS from the previous chapters as the starting point. Programmes vary from recognition only (a "hall of fame"), properly called a vulnerability disclosure programme, to substantial payments for critical findings.

Safe harbour. A written promise that the organisation will not pursue legal action against researchers who act in good faith within the policy, and that it will not ask others to. This is the clause that does the real work: it is the organisation stating that activity under the policy is authorised and will not be treated as an offence. A programme without a safe-harbour statement offers weaker assurance, and experienced researchers check for it before spending time.

Disclosure terms. Whether and when a researcher may publish, usually after a fix and with the organisation's agreement.

How a finding is reported and rewarded

The lifecycle of one bounty finding is the vulnerability lifecycle run quickly:

  1. The researcher tests within scope and finds a flaw.
  2. They write a report and submit it privately through the programme's platform.
  3. The organisation triages: reproduces it, assesses severity, may ask questions, and decides whether it is in scope and novel.
  4. If valid, they pay and credit, and fix the flaw.
  5. Public disclosure, if any, happens later and by agreement.

What a good report contains, because this is what separates a paid finding from a rejected one:

  • A clear title naming the flaw and where it is.
  • The affected target, exactly (URL, endpoint, parameter, application version).
  • Steps to reproduce, numbered, precise enough that a triager can follow them without guessing, including the accounts used.
  • Evidence: request and response, or a screenshot, with sensitive values masked.
  • Impact: what an attacker could actually achieve. This is the part researchers skimp and triagers care most about.
  • A suggested severity with a CVSS vector, and ideally a remediation suggestion.

"Your site is vulnerable to XSS" earns nothing. "The search parameter on this endpoint reflects input into the page without encoding; steps below; an attacker can run script in a victim's session and read their session token; suggested CVSS vector; fix by contextual output encoding" earns the reward and the fix.

Why reports get rejected, which is worth knowing before you write one:

  • Out of scope, the commonest reason by far.
  • Duplicate: somebody reported it first. Bounties usually pay only the first reporter, which is why speed matters and why disputes arise.
  • Not a vulnerability: accepted behaviour, or a theoretical issue with no demonstrable impact. Missing security headers with no exploitable consequence are the classic example.
  • No demonstrated impact: the researcher showed a quirk but not what an attacker gains.
  • Scanner output pasted in without verification or analysis, which most programmes explicitly refuse.
munotes.in74

Bug Bounty Programmes

A worked example

Priya reads the policy for a shopping company's programme: scope is *.example-shop.test; denial of service and social engineering are forbidden; rewards run from a small sum for Low to a large one for Critical; there is a clear safe-harbour clause; publication requires agreement.

  • She tests only subdomains of example-shop.test. She notices an interesting login portal on a different domain the same company owns and does not touch it, because the scope does not name it; instead she asks the programme whether it can be added. That single decision is the difference between a researcher and a defendant.
  • She finds that a password-reset link remains valid after use, so an old link found in a forwarded email or a browser history could be replayed to take over an account.
  • She writes it up: the endpoint, the exact steps with two of her own test accounts, the masked evidence, the impact (account takeover without the victim's password), a CVSS vector suggesting Medium, and the fix (invalidate the token on first use and on password change).
  • The company confirms it, pays the Medium band, credits her, and ships the fix. She publishes nothing until they agree.

Compare this with the grey hat of the earlier chapter, who found a flaw on a stranger's site uninvited: identical skill, identical technique, and an entirely different legal position. The bounty is the difference, and the difference is permission granted in advance.

What beginners get wrong

  • Reading a bounty as permission to test anything the company owns. The permission is exactly the published scope and no wider. A system the same company owns but did not list is unauthorised.
  • Assuming every programme pays. Many offer only recognition. Read the policy first.
  • Breaking the rules of engagement to "prove impact". Running a denial-of-service test inside a bounty that forbids it breaks the policy and the safe harbour, turning authorised testing back into an offence.
  • Publishing to get attention. Disclosing before the organisation agrees breaches the terms, forfeits the reward, and damages the trust the whole arrangement depends on.
  • Reporting scanner output. Programmes refuse it. A finding needs verification, impact and analysis.
  • Omitting impact. Triagers must justify payment internally; a report that does not explain what an attacker gains gives them nothing to justify.
  • Testing with real user data. Almost always forbidden, and it engages the confidentiality provisions of the Act. Use the test accounts provided.

Quick revision

  • A bug bounty is a standing, public authorisation to test named targets under published rules, rewarding valid findings. It grants permission in advance, which is what makes it lawful.
  • Parts: scope (the legal boundary, with exclusions), rules of engagement (usually forbidding denial of service, social engineering, real user data), reward structure (banded by severity, often CVSS-based), safe harbour (no legal action for good-faith work in policy), disclosure terms.
  • A vulnerability disclosure programme offers recognition without payment; a bug bounty pays.
  • A good report: title, exact target, numbered reproduction steps, masked evidence, impact, suggested severity and fix.
  • Rejections: out of scope, duplicate, not a vulnerability, no demonstrated impact, unverified scanner output.
  • A bounty complements a penetration test: breadth and continuity against structured, guaranteed coverage.
munotes.in75

Bug Bounty Programmes

Test yourself

  1. How does a bug bounty make testing lawful when uninvited testing is not?

It is a standing, public grant of permission to anyone who accepts its rules, so testing within its scope is authorised and does not fall under section 43's "without permission of the owner", which uninvited testing does regardless of motive.

  1. What is a safe-harbour clause, and why do experienced researchers check for it?

A written undertaking that the organisation will not take legal action against researchers acting in good faith within the policy. Researchers check for it because it is the organisation's explicit assurance that policy-compliant activity is authorised rather than an offence.

  1. A researcher on a bounty finds a promising system the company owns but which is not listed in scope. What should they do, and why?

Not test it, and ask for it to be added. Ownership by the company is not authorisation: the permission extends only to the published scope, so testing an unlisted system is unauthorised access.

  1. List four things a report must contain to be paid, and give the commonest reasons reports are rejected.

The exact affected target, numbered steps to reproduce, evidence with sensitive values masked, and a statement of impact (plus a suggested severity and fix). Reports are rejected chiefly for being out of scope, duplicates, not actually vulnerabilities, lacking demonstrated impact, or being unverified scanner output.

  1. How does a bug bounty differ from a penetration test as a way of finding flaws?

A bounty is continuous, pays per valid finding, and draws on many researchers, giving breadth but no guarantee of coverage. A penetration test is time-boxed and paid for effort, and gives structured, guaranteed coverage of an agreed scope with a report. They complement each other.

Contents This chapter on its own page

munotes.in76

Chapter Seventeen

A Worked Case Study: Heartbleed

Syllabus topic Module 1, "Vulnerability Research and Disclosure Mechanisms: ... Analyze a real vulnerability case study"

In one line

Heartbleed (CVE-2014-0160) was a missing length check in OpenSSL's heartbeat feature that let a remote attacker read up to 64 kilobytes of the server's memory at a time, repeatedly, leaving no trace. It scores 7.5, High, and it is the standard case study for how a small mistake in shared code becomes everybody's problem.

In examination wording: Heartbleed was a buffer over-read vulnerability disclosed in April 2014 in the OpenSSL cryptographic library's implementation of the TLS heartbeat extension, arising from a failure to validate that a client-supplied length field matched the actual payload, permitting unauthenticated remote disclosure of process memory.

Why this case study

It is worth analysing for five reasons, and each is a lesson the rest of the book depends on:

  1. The flaw itself is simple enough to understand completely, which is rare for a famous vulnerability.
  2. It shows that the most damaging flaws are often not clever; this one is a missing check.
  3. It demonstrates the supply-chain problem before that was a fashionable phrase: almost nobody ran "OpenSSL", they ran products that contained it.
  4. It is the clearest illustration of why confidentiality breaches cannot be undone, and of why "no trace in the logs" is a property of some attacks.
  5. Its disclosure is a good example of coordinated disclosure done largely right, with the fix and the advisory released together.

The mechanism, at concept level

TLS, the protocol behind HTTPS, has a heartbeat extension whose purpose is to keep a connection alive: one side sends a small message and asks the other to send it back, confirming the connection is still usable.

The message contains two things: some payload data, and a length field saying how long that payload is. The correct behaviour is to copy back exactly the payload that arrived.

The flaw was that the implementation believed the length field instead of checking it against the payload actually received. A client could send a one-byte payload while claiming the length was 64 kilobytes. The server would allocate a response buffer of the claimed size, copy the claimed number of bytes starting at the payload, and send it all back. The first byte was the real payload; the remaining 65,535 bytes were whatever happened to be next in the server's memory.

That is the whole bug. In the vocabulary of the earlier chapters it is a buffer over-read, classified as CWE-125 (out-of-bounds read); the fix was to check that the claimed length matched what was received and to discard the message otherwise.

What that memory contained was not chosen by the attacker, which is why it was so dangerous in aggregate: it was whatever the process had recently handled. Repeated requests returned different regions, so an attacker could keep asking and accumulate the contents. Over many requests that could include session cookies, usernames and passwords submitted by other users, message contents, and, in the worst case, the server's private key, which would let an attacker impersonate the site entirely.

munotes.in77

A Worked Case Study: Heartbleed

A worked example: reading Heartbleed with the module's tools

Which property broke? Confidentiality, and only confidentiality. Nothing was altered, nothing was destroyed, and the service kept running. That single observation predicts the score.

The CVSS vector. AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N:

  • Attack Vector Network: any client that could open a TLS connection.
  • Attack Complexity Low: it worked reliably every time.
  • Privileges Required None: no account, no authentication. The heartbeat could be sent before authentication.
  • User Interaction None: no victim had to do anything.
  • Scope Unchanged: the damage stayed within the vulnerable component's own security authority.
  • C:H, I:N, A:N: total confidentiality loss; no integrity or availability impact.

The score is 7.5. The previous chapter worked it by hand and the calculator reproduced it. The instructive point: the exploitability half was as bad as the model allows, and it still did not reach Critical, because two of three impact metrics were None. A student who can explain why Heartbleed is 7.5 rather than 10.0 has understood CVSS.

The lifecycle. The flaw was introduced in released code in 2012 and disclosed in April 2014, so it was live and unknown for roughly two years. It was found independently by more than one party at about the same time, which is the scenario coordinated disclosure most fears: once two people know, the timeline cannot be leisurely. A fixed version of OpenSSL was released on the day of public disclosure, so the advisory and the patch arrived together, which is the ideal the disclosure chapter described.

What made it worse than the score suggests

Three aggravating features, and they are the parts that generalise.

It left no trace. A heartbeat request is a normal protocol message. Exploiting the flaw did not crash anything, did not create an error, and was not recorded by ordinary server logs. So after disclosure, no organisation could determine whether it had been exploited. The honest position for every affected site was to assume the worst: rotate the private key, obtain a new certificate, revoke the old one, and require users to change passwords. An attack that leaves no evidence forces you to act as though it happened, which is far more expensive than responding to a known incident.

The private key was reachable. Most confidentiality breaches expose data. This one could expose the key that protects all future and, where forward secrecy was not in use, past traffic. Recovery therefore meant re-keying, not merely patching.

munotes.in78

A Worked Case Study: Heartbleed

Nobody knew where it was installed. Almost no organisation ran "OpenSSL" as a product they had chosen. They ran web servers, load balancers, VPN appliances, mail servers, embedded devices and vendor applications that contained OpenSSL. Patching required first discovering where it was, which many could not do quickly, and for appliances it meant waiting for a vendor update that sometimes never came. This is the supply-chain lesson, and it is why the OWASP list now carries a supply-chain category and why a software bill of materials matters.

The defensive analysis

Ask the four questions a case study should answer.

How was it found? By researchers auditing widely used cryptographic code, which is the argument for funding review of shared infrastructure. The flaw sat in code that vast numbers of systems depended on and very few people were paid to examine.

Which control would have prevented it? At the source, input validation: check the length field against reality. More broadly, memory-safe languages or bounds-checked buffer handling remove this entire class, which is the argument made in the buffer overflow chapters later. Static analysis and fuzzing target exactly this shape of defect.

Which control would have detected it? Essentially none in place at the time, which is the chapter's hardest lesson. Ordinary logging did not record it. Detection would have required inspecting heartbeat requests for a mismatch between claimed and actual length, which no one was doing because no one knew it mattered.

Which control would have limited the damage? Forward secrecy in the TLS configuration, which means that compromising the long-term private key does not let an attacker decrypt previously recorded sessions. Sites using it had a materially smaller problem. Rapid key rotation capability also limited it: organisations that could re-key and reissue certificates quickly recovered in days, and those that could not took months.

Lessons that generalise

  • Severity is not the whole story. A 7.5 caused a global emergency, because of ubiquity, invisibility and the reachability of the key. Base score plus context is the real measure.
  • Shared components concentrate risk. One mistake in one library affected a large fraction of the secure web at once.
  • You cannot respond to what you cannot see. Attacks that leave no evidence force expensive precautionary responses.
  • Inventory is a security control. The organisations that recovered fastest were the ones that could answer "where do we run this?" quickly.
  • Simple bugs cause the biggest incidents. A missing length check, not a sophisticated cryptographic break.

What beginners get wrong

  • Calling it an encryption flaw. TLS and its cryptography were not broken. The flaw was a memory-handling mistake in one implementation of one extension, and it leaked data that happened to be nearby.
  • Thinking it let an attacker choose what to read. It returned whatever was adjacent in memory. The attacker repeated it many times and sifted the results; control was statistical, not precise.
  • Assuming patching finished the job. Because the private key might have been exposed and there was no way to know, recovery required re-keying, new certificates, revocation, and user password changes.
  • Expecting logs to show exploitation. They did not. That is the point, and it is why the response had to be precautionary.
  • Treating it as an OpenSSL problem. It was a problem for everyone who shipped or ran anything containing OpenSSL, which was almost everyone.
munotes.in79

A Worked Case Study: Heartbleed

Quick revision

  • CVE-2014-0160, disclosed April 2014, in OpenSSL's TLS heartbeat extension. A buffer over-read (CWE-125): the code trusted the client's length field instead of checking it against the payload received, returning up to 64 KB of adjacent process memory per request.
  • Breaks confidentiality only; vector AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N, score 7.5, High. Not 10.0 because integrity and availability are unaffected.
  • Live and unknown for about two years; found independently by more than one party; fix and advisory released together, which is coordinated disclosure done right.
  • Aggravating factors: no trace in logs (forcing precautionary response), the private key was reachable (forcing re-keying), and it was embedded in countless products (the supply-chain problem).
  • Defences: validate the length (the direct fix), memory-safe or bounds-checked handling (the class fix), forward secrecy to limit the damage of key compromise, and an inventory so you can find where you run it.

Test yourself

  1. Explain the Heartbleed mechanism in two sentences.

The TLS heartbeat message carries a payload and a length field, and OpenSSL copied back the number of bytes the client claimed rather than the number actually received. A client claiming a large length with a tiny payload therefore received up to 64 kilobytes of whatever lay adjacent in the server's process memory.

  1. Why does Heartbleed score 7.5 rather than 10.0 when it is remotely exploitable, reliable, and needs no privileges or interaction?

Because the impact half is limited: it affects confidentiality only, with integrity and availability both None and Scope Unchanged. Maximal exploitability with partial impact yields a High rather than a Critical.

  1. Why was patching alone an inadequate response?

Because the server's private key might have been disclosed and exploitation left no trace, so no organisation could prove it had not happened. Recovery therefore required generating new keys, obtaining and deploying new certificates, revoking the old ones, and having users change passwords.

  1. What made Heartbleed a supply-chain problem, and which control most helped organisations respond?

Almost nobody ran OpenSSL as a chosen product; it was embedded in web servers, appliances, VPNs and vendor applications, so organisations first had to discover where it was. An accurate inventory of software components was what let the fastest responders act, and for appliances they depended on vendor updates.

munotes.in80

A Worked Case Study: Heartbleed

  1. Which configuration choice limited the damage for sites that had made it, and why?

Forward secrecy, because it ensures that compromise of the long-term private key does not permit decryption of previously recorded sessions. Sites using it faced a smaller retrospective exposure than those where the key alone would unlock past traffic.

Contents This chapter on its own page

munotes.in81

Chapter Eighteen

A Worked Case Study: Log4Shell

Syllabus topic Module 1, "Vulnerability Research and Disclosure Mechanisms: ... Analyze a real vulnerability case study"

In one line

Log4Shell (CVE-2021-44228) was a flaw in Log4j, a near-ubiquitous Java logging library, by which merely writing an attacker-controlled string to a log could cause the server to fetch and run code from a machine the attacker chose. It scores 10.0, the maximum, and it is the standard case study for supply-chain risk.

In examination wording: Log4Shell was a remote code execution vulnerability disclosed in December 2021 in Apache Log4j 2, arising from the library's message-lookup substitution feature performing JNDI lookups on attacker-controlled input, allowing an unauthenticated remote attacker to cause the logging host to retrieve and execute a remote class.

Why this case study

Heartbleed was a mistake. Log4Shell was, in a sense, the software doing what it was built to do, and that is why it is worth a chapter:

  1. The dangerous behaviour was a documented feature, not a bug in the ordinary sense, so code review looking for mistakes would not have flagged it.
  2. The trigger was logging, the one thing every application does with untrusted input, and does deliberately.
  3. It affected an enormous number of systems that had no idea they contained Log4j.
  4. It is the clearest illustration of scope change and of why that metric exists.
  5. Its defences illustrate the whole toolkit: patching, configuration, egress filtering, and inventory.

The mechanism, at concept level

Three ordinary design decisions combined into a catastrophe. Understanding the combination is the point; no single element is obviously wrong.

First, Log4j supported "lookups" in log messages. To make logging convenient, the library could substitute values into a message: a special marker in the text would be replaced with, say, an environment variable or a system property. This is a feature, documented and intended.

Second, one of those lookups could use JNDI. JNDI (the Java Naming and Directory Interface) is a standard Java mechanism for looking things up in a directory service, and it is capable of fetching an object from a remote server and materialising it in the running process. Again, a feature, and one with legitimate uses in enterprise Java.

Third, the substitution was applied to the message content itself, not just to the format string the developer wrote. So if an application logged a string that came from a user, and that string contained a lookup marker, the lookup was performed.

Put together: an attacker sends a request containing a crafted string in any field the application happens to log, a username, a search term, a user-agent header, an HTTP header of almost any kind. The application logs it, as it is supposed to. Log4j sees the marker, performs a JNDI lookup to a server the attacker specified, retrieves a Java class from it, and the process loads it. The attacker is now running code on the server.

munotes.in82

A Worked Case Study: Log4Shell

No authentication was needed, because applications log requests before and regardless of authentication. No user interaction was needed. And the attacker did not need to find a vulnerable input field in the usual sense, because any logged field would do, which made it nearly impossible to defend by filtering one place.

In the classification vocabulary, the root weakness is improper neutralisation of attacker-controlled input leading to code execution, with an element of unsafe deserialisation or remote class loading through JNDI.

A worked example: reading Log4Shell with the module's tools

Which properties broke? All three. The attacker could read data (confidentiality), alter it (integrity) and destroy or disable the service (availability), because running arbitrary code on a host gives all of it. Contrast Heartbleed, which broke only confidentiality, and the difference in score follows immediately.

The CVSS vector. AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H:

  • Attack Vector Network: any request reaching the application.
  • Attack Complexity Low: reliable, and the trigger string was short.
  • Privileges Required None: no account needed, because logging happens before authentication.
  • User Interaction None: no victim action required.
  • Scope Changed: this is the metric worth dwelling on. The vulnerable component was a logging library, whose security authority is, notionally, logging. Exploiting it gave control of the entire host process and whatever that process could reach, which is a different security authority altogether. That is exactly what Scope Changed is defined to capture, and it is why this flaw illustrates the metric better than any other.
  • C:H, I:H, A:H: total impact on all three.

The score is 10.0. The calculator in the CVSS chapter reproduced it. Nothing scores higher, and the combination that gets there is total impact plus scope change plus maximal exploitability.

What made it exceptionally hard to handle

Nobody knew where it was. Log4j is a dependency of a dependency of a dependency. Organisations ran Java applications, vendor appliances, cloud services and internal tools that contained it several layers down, often without the vendor knowing either. The first and hardest task was not patching; it was discovery. Teams spent days answering "do we even run this?" before they could begin to fix anything. This is the supply-chain lesson in its purest form, and the direct argument for a software bill of materials, a machine-readable inventory of every component in a product, which turns that multi-day question into a query.

The attack surface was everything. Because any logged string could carry the trigger, and applications log headers, usernames, search terms and error messages, there was no single input to validate. Attempts to block the pattern by filtering failed repeatedly, because the string could be obfuscated in many ways using the library's own nested-lookup capability. This is a general lesson: filtering a dangerous pattern is a weak control when the attacker controls the encoding.

munotes.in83

A Worked Case Study: Log4Shell

Exploitation began immediately and at scale. Because the flaw was trivial to trigger and the details public, mass internet-wide scanning for it started within hours of disclosure. The window between disclosure and exploitation was not days, it was hours, which is the practical demonstration of the point in the disclosure chapter about public disclosure raising short-term risk.

Fixes arrived in stages. The first mitigation turned out to be incomplete, and further advisories and versions followed as related issues were found. Organisations that patched once and stopped were not fully protected, which is a lesson in itself: for a flaw of this shape, track the advisory rather than applying one update.

The defensive analysis

Which control would have prevented it? At the library, not performing lookups on message content, which is what the fix did (the behaviour was disabled by default in later versions). At the application, nothing reasonable: the developers did nothing wrong by logging user input, which is precisely why this case is disturbing.

Which control would have limited it? Egress filtering, and this is the most transferable lesson in the chapter. The exploit required the victim server to make an outbound connection to the attacker's machine to fetch the class. A server that is not permitted to open arbitrary outbound connections to the internet could be triggered but could not complete the attack. Most organisations allow unrestricted outbound traffic from servers because it is convenient; those that did not were substantially protected by a control they had put in place for unrelated reasons.

Two others: least privilege, so that the code ran with limited rights and reached less; and network segmentation, so the compromised host could not reach everything else.

Which control would have detected it? Outbound connection logging, because the tell-tale sign is a server suddenly making connections to an unfamiliar external address. This is a good example of detection being available to organisations that log the right thing, which is usually egress rather than ingress.

Which control made response possible? Inventory, again. The organisations that responded in hours rather than weeks were those that already knew their software components.

Heartbleed and Log4Shell compared

Heartbleed (2014)Log4Shell (2021)
Root causeA coding mistake (missing length check)A feature reached by untrusted input
Weakness classOut-of-bounds readUnsafe lookup leading to code execution
Properties brokenConfidentiality onlyConfidentiality, integrity and availability
ScopeUnchangedChanged
CVSS7.5 High10.0 Critical
Attacker gainsFragments of memory, possibly the keyArbitrary code execution on the host
Trace leftNone in ordinary logsOutbound connection, if egress is logged
Hardest part of responseRe-keying, because exposure was unprovableFinding where the component was installed
Generalisable lessonShared code concentrates risk; invisible attacks force precautionary responseSupply chain; features can be vulnerabilities; egress filtering limits damage
munotes.in84

A Worked Case Study: Log4Shell

Studying the pair is more instructive than either alone, because the contrast isolates what is common: both were in shared components, both were reachable by unauthenticated remote input, and in both cases the decisive factor in recovery was whether the organisation knew what it was running.

What beginners get wrong

  • Calling it a bug in logging. The library did what it was documented to do; the flaw was that a convenience feature was applied to untrusted content. That is a design failure, not a coding slip.
  • Thinking the application developers were careless. Logging user input is normal and correct. This is the case that shows a safe application can be compromised through a dependency.
  • Believing input filtering was a fix. The trigger could be obfuscated using the library's own features, and attempts to block it by pattern failed. Removing the capability was the fix.
  • Assuming a single patch closed it. Follow-up advisories addressed related issues; tracking the advisory was necessary.
  • Missing why Scope is Changed. The vulnerable component was a logging library; the impact was control of the whole host process, which is a different security authority.
  • Overlooking egress filtering. The exploit needed an outbound connection from the victim to the attacker. Blocking that broke the chain, and it is the control most organisations still do not apply.

Quick revision

  • CVE-2021-44228, December 2021, Apache Log4j 2. A documented message-lookup feature performed JNDI lookups on attacker-controlled log content, causing the host to fetch and execute a remote class.
  • Triggered by logging any attacker-supplied string (a header, a username, a search term), before authentication, with no user interaction.
  • Vector AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H, score 10.0. Scope Changed because a logging library's flaw yielded control of the whole host.
  • Hard to handle because organisations did not know they contained it (a dependency of a dependency), the trigger could appear in any logged field, filtering could be obfuscated around, exploitation began within hours, and fixes came in stages.
  • Controls: remove the capability (the real fix); egress filtering, which breaks the required outbound fetch; least privilege and segmentation to limit reach; outbound connection logging to detect; and a software bill of materials to make response possible.
  • Against Heartbleed: a feature rather than a mistake, all three properties rather than one, Scope Changed rather than Unchanged, 10.0 rather than 7.5.

Test yourself

  1. Explain the Log4Shell mechanism and why the application developers were not at fault.
munotes.in85

A Worked Case Study: Log4Shell

Log4j substituted lookups into log message content, and one lookup type used JNDI, which can fetch and load a class from a remote server. Because the substitution applied to the message content, logging an attacker-supplied string caused the host to fetch and execute attacker-chosen code. Developers were not at fault because logging user-supplied input is normal and correct; the dangerous behaviour was inside the dependency.

  1. Why is Scope recorded as Changed, and what does that contribute to the score?

Because the vulnerable component was a logging library, whose security authority is logging, while successful exploitation yielded arbitrary code execution over the entire host process and what it could reach, which belongs to a different authority. Scope Changed raises the impact calculation and multiplies the combined score by 1.08, helping it reach the maximum 10.0.

  1. Why was input filtering an inadequate response?

Because the trigger string could be obfuscated in many forms using the library's own nested-lookup capability, and because the input could arrive in any field the application logged, so there was no single place to filter. The effective fix was to remove the lookup capability.

  1. Which network control would have broken the attack chain even on an unpatched server, and why?

Egress filtering. Exploitation required the victim server to make an outbound connection to the attacker's machine to retrieve the class, so a server not permitted to open arbitrary outbound internet connections could be triggered but could not complete the attack.

  1. Compare Heartbleed and Log4Shell in terms of root cause, properties broken and the hardest part of the response.

Heartbleed was a coding mistake (a missing length check) that broke confidentiality only, and its hardest response problem was re-keying, because exploitation left no trace and could not be disproved. Log4Shell was a documented feature reached by untrusted input, broke all three properties with Scope Changed, and its hardest response problem was discovering where the component was installed, since it was an indirect dependency.

Contents This chapter on its own page

munotes.in86

Chapter Nineteen

Footprinting: Passive Against Active Reconnaissance

Syllabus topic Module 1, "Footprinting and Information Gathering Methodology: Explore passive and active reconnaissance techniques including OSINT, competitive intelligence, and search engine reconnaissance strategies"

In one line

Footprinting is building a picture of a target from information that is already available. Passive reconnaissance uses third parties and never touches the target's systems; active reconnaissance touches them. The line between the two is technical, and it is also the line at which section 43 starts to apply.

In examination wording: footprinting is the first phase of an engagement, the systematic gathering of information about a target in order to build a profile of its people, technologies and infrastructure; open-source intelligence is information collected from publicly available sources; passive reconnaissance obtains information without interacting with the target's systems, while active reconnaissance involves direct interaction and therefore requires authorisation.

Why reconnaissance decides the engagement

The lifecycle chapter claimed this is the phase with the highest return, and it is worth setting out why, because students consistently want to skip to scanning.

An attacker's problem at the start is that the target is large and unknown. They do not know which systems exist, which are neglected, what software is running, who works there, or what the email format is. Every one of those unknowns is expensive to resolve by brute force and cheap to resolve by reading.

Reconnaissance converts a large unknown problem into a small, specific one. After a thorough passive phase an attacker may know: seven subdomains including one called test-portal that nobody has thought about in three years; that the organisation runs a particular version of a content management system, because a job advertisement said so; the names of eleven staff and the pattern of their email addresses; and which third party handles their payments. Nothing in that list required touching the target's systems, and all of it narrows everything that follows.

The defensive corollary is the reason this block matters to a student who never intends to attack anything: you can run the same process against your own organisation, and everything you find is something you can choose to remove. That is the subject of the last chapter in this block, and it is the most immediately useful thing in the module.

Passive reconnaissance

Passive reconnaissance gathers information without any interaction with the target's systems. The information comes from third parties: search engines, public registries, social media, news, government filings, code repositories, certificate logs, and archives.

The defining property is that from the target's point of view, nothing happened. Their logs contain no record of you, because you never connected to them. You read a copy of their information held by somebody else.

Examples, each expanded in the chapters that follow:

  • Reading the organisation's public website through a search engine's cache rather than directly.
  • Looking up domain registration data.
  • Reading staff profiles on professional networks.
  • Searching public code repositories for the organisation's name.
  • Reading certificate transparency logs, which record certificates issued for a domain and therefore reveal host names.
  • Reading archived copies of pages that have since been removed.
munotes.in87

Footprinting: Passive Against Active Reconnaissance

Legally, passive reconnaissance reads information that is already public and does not touch the target's computers, so it does not engage section 43, which turns on access to a computer, computer system or network without permission. Reading a public web page is not unauthorised access to the publisher's computer in the sense the section addresses.

Two qualifications a careful student should hold. Privacy law is a separate question from the IT Act: compiling a detailed profile of identifiable individuals can raise data-protection issues even where each fact is public, which is why professional engagements restrict people-focused reconnaissance to what the scope requires. And the platform's terms may prohibit automated collection, which is a contractual matter rather than a criminal one but can still cause trouble.

Active reconnaissance

Active reconnaissance interacts with the target's systems. The moment you send a packet to a machine the target owns, you have left the passive world.

Examples:

  • Resolving a host name against the target's own authoritative name server (as opposed to a public resolver's cache).
  • Connecting to a web server to read its response headers.
  • Requesting a page directly rather than through a cache.
  • Attempting a DNS zone transfer.
  • Any port scan, though scanning is usually treated as its own phase.

The defining property is the mirror image: the target's systems now hold a record of you. Web server logs, DNS query logs, firewall logs and intrusion detection systems can all see active reconnaissance, and a competent defender can detect it.

Legally, this is where section 43 begins to apply. Touching a computer system without permission is an act under clause (a), and the section requires neither damage nor dishonest intent. So the practical rule for a student is blunt: passive reconnaissance against anyone is generally fine; active reconnaissance happens only against systems you own or are authorised in writing to test.

The line is blurrier than it looks

Three cases that examiners like, and that a thoughtful answer acknowledges.

Visiting a website. Loading a company's public home page in a browser technically connects to their server, so it is interaction. In practice nobody treats ordinary browsing of a public page as active reconnaissance, because the page is published for that purpose and the visit is indistinguishable from any other visitor's. The distinction that matters is intent and pattern: one ordinary page view is browsing; a thousand automated requests enumerating paths is active reconnaissance and is visible as such.

DNS resolution. Asking a public resolver for a record usually returns a cached answer and never reaches the target: passive. Asking the target's own authoritative name server reaches their machine: active. Same question, different route, different side of the line.

munotes.in88

Footprinting: Passive Against Active Reconnaissance

Third-party services. If the target's website is hosted by a provider, touching it touches the provider's infrastructure too, which is why scopes name third parties explicitly and why the client cannot authorise testing of systems it does not own.

The professional resolution is not to reason about these at the keyboard. It is to have the scope settled first, which is what the authorisation chapter was for.

Competitive intelligence and OSINT

MU's bullet names competitive intelligence alongside OSINT, and the relationship is worth stating: they are the same activity done for different purposes.

Open-source intelligence (OSINT) is the collection and analysis of publicly available information to produce actionable knowledge. The term comes from the intelligence community, and the important word is analysis: OSINT is not a pile of facts, it is what the facts mean when combined.

Competitive intelligence is the lawful gathering of public information about commercial rivals: their products, hiring, suppliers, financial filings and strategy. Businesses do it openly and it is a recognised profession.

The overlap is nearly total in technique, and the difference is purpose. A competitive-intelligence analyst reading a job advertisement notes that a rival is expanding into a new area; a security researcher reading the same advertisement notes that it names the exact version of the software the company runs. The same public sentence answers both questions, which is precisely why organisations underestimate what they publish: the person writing the job advertisement is thinking about recruitment, not about disclosing a software inventory.

The aggregation problem

The single most important idea in this block, and the one that makes reconnaissance dangerous despite every individual fact being harmless.

Consider four facts, each of which a company would publish without hesitation:

  1. A press release naming the new Head of Finance.
  2. A conference talk by an engineer describing the company's architecture.
  3. A job advertisement seeking an administrator for a named product at a named version.
  4. A support page giving the format of employee email addresses.

Individually, none is sensitive. Combined, they give an attacker a named target, their likely email address, a known-vulnerable software version to look up, and an understanding of the internal architecture sufficient to write a convincing message. That is a spear-phishing campaign assembled entirely from material the company chose to publish.

The lesson for a defender is that footprint reduction cannot proceed fact by fact, asking "is this sensitive?", because the answer is almost always no. It has to ask "what does this enable when combined with everything else we publish?"

munotes.in89

Footprinting: Passive Against Active Reconnaissance

A worked example

Karan is authorised to assess his own college's public exposure before an attacker does. He begins passively and touches nothing:

  • The college website lists department heads with addresses in the form firstname@college.test. He now knows the email format for everyone in the institution.
  • An IT job advertisement from four months ago names the learning-management system and its version. He looks the version up and finds two published vulnerabilities.
  • Certificate transparency logs, which record certificates issued for the college's domain, list a host called results-old.college.test that appears nowhere on the website.
  • An archived copy of a page removed last year still shows an internal phone directory.

At this point Karan has not sent a single packet to the college. Everything came from third parties. He has the email format, a software version with known flaws, a forgotten host, and a staff directory.

Only now, and only because his authorisation names the college's systems, does he move to active reconnaissance: resolving results-old.college.test against the college's name servers to see whether it still exists, and reading its response headers. That step touches college systems and is lawful only because of the letter in his file.

His report separates the two halves, and the passive half is the more alarming, because it is the part the college can fix by changing what it publishes rather than by patching anything.

What beginners get wrong

  • Skipping reconnaissance because it does not feel like hacking. It is the phase with the highest return, and omissions here silently limit everything after.
  • Believing "passive" means "safe to do to anyone" without qualification. It does not engage section 43, but privacy law and platform terms are separate questions, and professional scopes limit people-focused collection.
  • Thinking active reconnaissance begins at scanning. It begins the moment you touch the target's systems, which can be a single direct DNS query or a header read.
  • Assessing published facts one at a time. The risk is in aggregation; individually harmless facts combine into an attack profile.
  • Treating footprint reduction as hiding. You are not hiding from a determined attacker; you are declining to hand out free information.
  • Forgetting that competitive intelligence uses the same sources. The job advertisement written for recruiters is read by attackers.

Quick revision

  • Footprinting builds a profile of a target; OSINT is publicly available information plus the analysis that makes it useful.
  • Passive: no interaction with the target's systems, information from third parties, leaves no trace in their logs, does not engage s.43. Active: touches their systems, leaves a trace, needs written authorisation.
  • Blurry cases: ordinary browsing (intent and pattern decide), public resolver (passive) against the target's own name server (active), and third-party hosting.
  • Competitive intelligence is the same technique for commercial purposes; the same published sentence serves both readers.
  • The aggregation problem: individually harmless facts combine into a targeted attack. Assess what you publish as a set, not item by item.
  • Do the whole process against your own organisation; what you find is what you can remove.
munotes.in90

Footprinting: Passive Against Active Reconnaissance

Test yourself

  1. Distinguish passive from active reconnaissance, and state the legal consequence of the distinction.

Passive reconnaissance obtains information from third parties without interacting with the target's systems, so it leaves no trace in their logs and does not engage section 43. Active reconnaissance interacts directly with the target's systems, is recorded by them, and constitutes access that requires written authorisation.

  1. Give a case where the same question is passive or active depending on how it is asked.

A DNS lookup: querying a public resolver usually returns a cached answer and never reaches the target, which is passive; querying the target's own authoritative name server reaches their machine and is active.

  1. What is the aggregation problem, and why does it defeat a fact-by-fact review of what an organisation publishes?

Individually harmless public facts combine into an actionable attack profile, for example a staff name, an email format, a software version and an architecture description together enabling targeted phishing against a known-vulnerable system. A fact-by-fact review asks "is this sensitive?" and almost always answers no, missing what the set enables.

  1. How do OSINT and competitive intelligence relate?

They are substantially the same collection and analysis of public information, differing in purpose: competitive intelligence seeks commercial insight about rivals, security reconnaissance seeks attack-relevant detail. The same published source, such as a job advertisement, commonly serves both.

  1. Why is reconnaissance described as the phase with the highest return?

Because it converts a large, unknown target into a small, specific one before any suspicious contact: it reveals which systems exist, which are neglected, what software and versions are in use, and who works there, narrowing what every later phase must attempt.

Contents This chapter on its own page

munotes.in91

Chapter Twenty

OSINT on People: Names, Roles and the Email Format

Syllabus topic Module 1, "Footprinting and Information Gathering Methodology: ... OSINT, competitive intelligence"

In one line

Attackers gather who works there, what they do, and how to write to them. One published email address usually reveals the format for the entire organisation, and a staff list plus a format is the raw material of every targeted phishing campaign.

In examination wording: people-focused open-source intelligence is the collection of publicly available information about an organisation's personnel, including names, roles, reporting relationships, contact formats and professional interests, in order to identify targets for social engineering and to infer organisational structure and technology.

Why people are reconnoitred first

The social-engineering block will show that attacking a person is often easier than attacking a system, and an attack on a person requires knowing which person. So this is where a targeted attack begins.

What an attacker wants from this phase is four things:

  1. Names and roles, to choose a target. A finance clerk who can move money, an IT administrator with privileges, or a new joiner who does not yet know the norms.
  2. The email format, so they can write to anyone in the organisation, including people who have never published an address.
  3. Reporting relationships, so a message can plausibly claim to come from someone with authority over the recipient.
  4. Context, the details that make a message convincing: a recent event, a project name, a supplier's name, a shared interest.

Every one of those is routinely published by organisations for good reasons.

The email format: one address gives you all of them

This is the highest-value single item in people-focused reconnaissance and the one organisations most underestimate.

Most organisations use a consistent pattern: firstname.lastname@, firstinitiallastname@, firstname@, or similar. Publishing one address, on a contact page, in a press release, in a conference programme, or in the metadata of a document, reveals the pattern. Combine the pattern with a list of staff names, which is usually easy to obtain, and an attacker can construct a valid address for every employee, including those who have never published one.

Two consequences follow:

  • Withholding individual addresses does not help much once the pattern is known. The defence is not to hide addresses one at a time.
  • The addresses can be verified. Some mail systems reveal whether an address exists, either through their own behaviour or through an enumeration weakness in a login or password-reset page. That is covered in the enumeration chapter, and it turns a constructed list into a confirmed one.

The realistic defences are therefore elsewhere: technical controls that make forged mail harder to deliver (the email authentication chapter), multi-factor authentication so that a phished password is insufficient, and training so that people recognise the message.

The sources

The organisation's own website. Leadership pages, "about us", press releases, annual reports and contact pages. Organisations publish senior staff deliberately, and senior staff are exactly who a business-email-compromise attack wants to impersonate.

munotes.in92

OSINT on People: Names, Roles and the Email Format

Professional networking sites. The richest source by a distance. They give names, job titles, tenure, the technologies people list as skills, and often the reporting structure inferred from titles. A new joiner announcing their role is announcing that they do not yet know who normally asks them for things.

Conference talks and publications. An engineer describing their architecture at a meetup is doing something professionally valuable and is also describing the internal systems.

Social media. Personal accounts leak context: a holiday (so the person is away and cannot be consulted), a team photograph (badges, screens, office layout), interests that can be used to build rapport.

Job advertisements. Simultaneously a people source and a technology source; they reveal team structure, seniority and gaps.

Document metadata, covered in a later chapter, which often carries author names and internal user names.

Breach data. Credentials exposed in other organisations' breaches, which matter because of password reuse. A professional tester usually checks only whether an organisation's addresses appear in known breaches, without obtaining or using the credentials, because the credentials are not theirs and handling them raises the issues in the law chapters.

The limits a professional keeps

This is the chapter where the subjects are people, so the boundaries are firmer than elsewhere, and a student should be able to state them.

Only what the scope permits. If the engagement forbids social engineering, then collecting a detailed dossier on named employees serves no authorised purpose. The reconnaissance should go no further than the engagement needs.

Public sources only, and no deception to obtain more. Reading a public profile is passive reconnaissance. Creating a false identity to connect to employees and draw information from them is pretexting, a social-engineering technique, and it needs explicit authorisation because it engages section 66D.

Never their personal accounts. Attempting to access an individual's own accounts is unauthorised access to that individual's systems, and the client cannot authorise it because the client does not own them.

Handle the results as personal data. Names, roles and addresses are personal data. They are stored securely, minimised to what the finding requires, redacted in the report, and destroyed at the end of the engagement, for the reasons in the confidentiality chapter.

Write findings about the organisation, not about individuals. A report should say "the email format is discoverable and a staff list is publicly available, enabling targeted phishing", not "this named employee overshares on social media". The finding is a systemic one and naming individuals invites blame that is both unfair and counterproductive, since the earlier chapter on social engineering will show that a blame culture makes people hide their mistakes.

munotes.in93

OSINT on People: Names, Roles and the Email Format

A worked example, run defensively

Nisha assesses her own organisation's people exposure, within a scope that permits reconnaissance but forbids any contact with staff.

  • The website's leadership page gives six names with addresses as firstname.lastname@company.test. Finding: the email format is public.
  • A professional networking search returns around eighty employees with titles. Combined with the format, she can construct eighty addresses without touching anything. Finding: a near-complete staff list plus format is available.
  • Three engineers list, as skills, the exact technologies and versions the company runs. Finding: the technology stack is inferable from staff profiles.
  • A recent press release names a new Chief Financial Officer who started six weeks ago. Finding: a high-value impersonation target who is new and may not know the organisation's norms.
  • A conference talk by a staff engineer describes the internal deployment pipeline. Finding: internal architecture is publicly described.

She writes these as five organisational findings with one recommendation set: publish role-based addresses where possible, brief new senior staff on impersonation risk in their first week, review what is said in public talks, and, because none of this can be fully prevented, ensure multi-factor authentication and a verification procedure for payment changes so that a convincing message cannot by itself cause harm. She names no individual.

That last move is the chapter's point: since you cannot stop people being findable, the defences must make finding them insufficient.

What beginners get wrong

  • Trying to hide employees. It is neither possible nor desirable; people need public professional identities. Reduce specific leaks (exact versions, internal architecture) and invest in controls that survive a convincing message.
  • Thinking withholding addresses protects them. Once the format is known, every address can be constructed. The pattern is the exposure, not the individual address.
  • Blurring reading a public profile with contacting the person. The first is passive; the second is social engineering and needs explicit authorisation.
  • Collecting more than the engagement requires. People-focused reconnaissance without an authorised purpose is a privacy problem, not thoroughness.
  • Naming individuals in findings. Findings are about the organisation's exposure. Naming people invites blame and discourages the reporting culture that limits damage.
  • Touching employees' personal accounts. The client cannot authorise access to systems it does not own.

Quick revision

  • Attackers seek names and roles (to choose a target), the email format (to write to anyone), reporting relationships (for plausible authority) and context (to be convincing).
  • One published address reveals the pattern for the whole organisation; withholding individual addresses does not help. Mail systems and login pages may then confirm which constructed addresses are real.
  • Sources: the organisation's own site, professional networks (richest), conference talks, social media, job advertisements, document metadata, and breach data (checked, not used).
  • Professional limits: only what the scope requires; public sources only, with no deception (pretexting needs authorisation and engages s.66D); never personal accounts; treat results as personal data; write findings about the organisation, not individuals.
  • Because people cannot be hidden, the real defences are multi-factor authentication, verification procedures for sensitive actions, email authentication, and training.
munotes.in94

OSINT on People: Names, Roles and the Email Format

Test yourself

  1. Why is a single published email address a significant exposure?

Because it reveals the organisation's address format, which combined with an easily obtained staff list lets an attacker construct a valid address for every employee, including people who have never published one. The pattern, not the individual address, is the exposure.

  1. Name four things an attacker seeks from people-focused reconnaissance and what each enables.

Names and roles, to select a target with the access or authority required; the email format, to reach anyone; reporting relationships, so a message can plausibly claim authority over the recipient; and contextual detail such as projects, suppliers or recent events, to make the message convincing.

  1. Where is the line between passive people reconnaissance and social engineering?

Reading publicly available profiles and publications is passive and touches no one. Creating a false identity to connect with employees and elicit information is pretexting, a social-engineering technique which requires explicit authorisation in the scope and engages section 66D.

  1. Why should findings about people exposure be written about the organisation rather than about named individuals?

Because the exposure is systemic and largely unavoidable for people who need public professional identities, and because naming individuals assigns blame unfairly and discourages the open reporting culture that limits damage when someone is deceived.

  1. Given that employees cannot be made unfindable, what defences actually reduce the risk?

Controls that make a convincing message insufficient: multi-factor authentication so a phished password does not grant access, verification through a second known channel for sensitive actions such as changing payment details, email authentication to make forgery harder to deliver, and training so people recognise the techniques.

Contents This chapter on its own page

munotes.in95

Chapter Twenty-One

OSINT on Technology and Infrastructure

Syllabus topic Module 1, "Footprinting and Information Gathering Methodology: ... OSINT, competitive intelligence"

In one line

Attackers work out what you run and where it lives, because a product plus a version becomes a list of known vulnerabilities, and a list of hosts becomes a list of places to try them.

In examination wording: technology-focused open-source intelligence identifies the software, versions, platforms and hosting arrangements an organisation uses, and enumerates its hosts and address space, so that known vulnerabilities affecting those components can be identified and the attack surface mapped.

Why a version number is the prize

The vulnerability chapters established the pipeline: a CVE names a flaw in a specific product at specific versions, and the National Vulnerability Database records which versions are affected. So an attacker who learns that you run a particular product at a particular version can look up, in seconds, every published flaw that applies to you, with its severity and often a description of how it works.

That is why "we run version 4.2.1" is a more dangerous sentence than it looks, and why the defensive half of this chapter is largely about not saying it.

The same pipeline explains why old information is still useful to an attacker. A job advertisement from a year ago naming a version tells them what you ran then, which strongly suggests what you run now, because organisations upgrade slowly.

Sources of technology intelligence

HTTP response headers. A web server commonly announces itself: the server product, sometimes its version, the application framework, and the programming language. This is the most direct source, though reading headers requires connecting to the server, which makes it active reconnaissance under the previous chapter's line.

Error pages. A default or verbose error page frequently names the product, the version and sometimes internal file paths. This is why the web-server hardening chapter treats generic error pages as a control rather than a cosmetic choice.

Page source. The names of scripts, stylesheets and frameworks, and often explicit version strings in the paths of library files. A page loading a named JavaScript library at a given version has disclosed a component and its version, and client-side libraries have CVEs like anything else.

Job advertisements. Consistently one of the most productive sources, and entirely passive. An advertisement seeking an administrator for a named product, at a named version, with named supporting technologies, is a description of the internal estate written by the organisation itself.

Staff profiles and talks, from the previous chapter, which list technologies as skills.

Public code repositories. Organisations publish code, and employees contribute to public projects from work accounts. What leaks here: configuration files showing internal host names, references to internal services, and, too often, credentials committed by accident. A professional searching a public repository for an organisation's domain name is doing passive reconnaissance; a finding of a committed secret is a serious one, and the correct handling is to report it so it can be revoked, not to use it.

munotes.in96

OSINT on Technology and Infrastructure

Certificate transparency logs. These deserve explanation because they are the source students have not met. When a certificate authority issues a TLS certificate, it publishes a record in a public, append-only log, so that mis-issued certificates can be detected. The logs are open to anyone, and every record names the host names the certificate covers. So an organisation that obtains a certificate for staging.company.test has published that host name to the world, whether or not it appears anywhere else. For subdomain discovery this is often the single most effective passive source, and it cannot be opted out of, because the transparency is the point.

Public search services that index internet-facing hosts. Services exist that continuously scan the internet, recording what responds on each address: banners, certificates, technologies. Querying one of them is passive from the target's point of view, because the service did the scanning, not you, and the target saw the service. This is a genuinely useful distinction: an attacker can learn much of what a scan would tell them without ever scanning.

DNS records and address allocations, which are the next two chapters.

Archived copies of pages. Web archives keep copies of pages that have since been changed or removed, so a removed page naming an internal system may still be readable.

What the attacker builds

The output of this phase is a technology profile: a list of products, versions and hosting arrangements, and a list of hosts and address ranges.

An example of the shape:

ObservationSourceWhat it enables
Web server product and versionResponse headersLook up CVEs for that version
Content management system and plugin versionsPage source and pathsLook up CVEs, especially for plugins
Cloud provider and regionDNS and certificate dataKnow the platform and its default weaknesses
Mail handled by a named providerDNS MX recordsCraft convincing provider-branded phishing
Seven subdomains including staging.Certificate transparencyIdentify neglected hosts
Address range allocated to the organisationRegistry dataKnow what is in scope to scan
A committed API keyPublic repositoryA credential to report, or to abuse

Each row is individually modest and together they define exactly where an attacker will spend their effort.

The defensive reading

Every source above has a control, and they divide into three kinds.

Say less. Suppress version numbers in headers and error pages; use generic error pages in production; avoid naming exact versions in job advertisements (say "experience with the product" rather than "version 4.2.1"); review what is said in public talks about internal architecture.

munotes.in97

OSINT on Technology and Infrastructure

Publish deliberately. Some disclosure is unavoidable and fine. The aim is not secrecy but avoiding needless specificity, because obscurity is not a security control and a determined attacker will fingerprint your software anyway. Which leads to the third and most important kind.

Make the knowledge useless. The real defence against "the attacker knows our version" is that the version has no unpatched known flaw. Patch management, which gets its own chapter later, is what turns an accurate technology profile into a dead end. An attacker who knows exactly what you run and finds it fully patched has gained very little.

Two specific controls deserve naming:

  • Monitor certificate transparency logs for your own domains. Because you cannot prevent certificate host names being published, watch them instead: it tells you what your own organisation has provisioned, which often surprises the security team, and it detects certificates issued for your names that you did not request.
  • Scan your own public repositories for secrets, and rotate anything found. Committed credentials are a recurring and serious exposure. Automated secret scanning in the build pipeline prevents recurrence, and the response to a leaked credential is always revocation, never deletion of the commit, because the history remains.

A worked example

Ravi is assessing his organisation's technology exposure, passively at first.

  • Certificate transparency lists eleven host names for the domain. Six are on the website; five are not, including vpn-test.company.test and old-portal.company.test. Finding: five hosts exist that are not publicly linked, two with names suggesting they are unmaintained.
  • A job advertisement from eight months ago names the ERP product and its version. He looks the version up: three published vulnerabilities, one rated High. Finding: the software estate is disclosed publicly, and a High-severity flaw may apply.
  • A public repository belonging to the organisation contains a configuration example with an internal host name and a database user name. Finding: internal naming is disclosed.
  • A public host-indexing service shows the response banners for the company's address range, including a web server version on a host nobody had mentioned. Finding: an unlisted internet-facing host exists.

None of this touched company systems. His recommendations follow the three kinds above: retire or patch the five unlinked hosts (the urgent one), stop naming versions in advertisements, add secret and configuration scanning to the repository pipeline, monitor certificate transparency for the domain, and confirm the ERP is patched, since that is what actually neutralises the disclosure.

What beginners get wrong

  • Thinking header suppression is the fix. It slows an attacker slightly; fingerprinting usually identifies the software anyway. Patching is the control that matters, and the obscurity is a minor supplement.
  • Ignoring client-side libraries. A JavaScript library named at a version in the page source is a component with its own CVEs.
  • Missing certificate transparency. It is public, unavoidable, and often the best subdomain source. Organisations are frequently unaware they are publishing host names this way.
  • Treating an internet-indexing service's data as an active scan. Querying it is passive from the target's viewpoint, because the service did the scanning. That is exactly why attackers use it first.
  • Deleting a committed secret instead of revoking it. The commit history retains it. The only correct response is to rotate the credential.
  • Assuming old information is stale. Organisations upgrade slowly, so a year-old advertisement is often still accurate.
munotes.in98

OSINT on Technology and Infrastructure

Quick revision

  • The aim is a technology profile: products, versions, hosting, plus hosts and address ranges. A product and version becomes a CVE list.
  • Passive sources: job advertisements, staff profiles and talks, public code repositories (including committed secrets), certificate transparency logs (excellent for subdomains, unavoidable), internet-wide indexing services (passive from the target's view), web archives, DNS and registry data.
  • Active sources: response headers, error pages, direct page requests.
  • Controls in three kinds: say less (suppress versions, generic errors, vaguer advertisements), publish deliberately (obscurity is not security), and make the knowledge useless by patching, which is the real defence.
  • Specifically: monitor certificate transparency for your own domains, and scan repositories for secrets, rotating anything found rather than deleting the commit.

Test yourself

  1. Why is a product version number the most valuable single item in technology reconnaissance?

Because CVE records identify flaws in specific products at specific versions, so a product and version can be looked up directly against vulnerability databases to produce a list of known flaws, their severity and often how they work.

  1. What are certificate transparency logs, and why are they so useful for subdomain discovery?

They are public, append-only logs in which certificate authorities record every certificate issued, so that mis-issuance can be detected. Each record names the host names the certificate covers, so obtaining a certificate for an internal-sounding host publishes that name; the logs cannot be opted out of, since publication is the mechanism's purpose.

  1. Why is querying an internet-wide host-indexing service considered passive?

Because the service performed the scanning and the target's logs record the service, not the researcher. The researcher reads a third party's records, so the target's systems are never touched.

  1. Is suppressing version banners an adequate defence, and what is?

It is not adequate, because software can usually be fingerprinted from its behaviour regardless. The effective defence is patch management, so that an accurate technology profile leads to no unpatched known vulnerability; banner suppression is a minor supplementary measure.

  1. A credential is found committed in a public repository. What is the correct response and why is deleting the commit insufficient?
munotes.in99

OSINT on Technology and Infrastructure

Revoke and rotate the credential immediately. Deleting the commit is insufficient because the repository history, and any clone or cached copy taken before deletion, still contains the secret, so only invalidating the credential removes the exposure.

Contents This chapter on its own page

munotes.in100

Chapter Twenty-Two

Search-Engine Reconnaissance and Document Metadata

Syllabus topic Module 1, "Footprinting and Information Gathering Methodology: ... search engine reconnaissance strategies"

In one line

Search engines index far more than an organisation intends, and precise queries retrieve the parts that were never meant to be found. Published documents carry hidden metadata, author names, internal paths, software versions, that the author did not know they were sending.

In examination wording: search-engine reconnaissance uses advanced search operators to locate indexed content that an organisation did not intend to expose, such as directory listings, administrative interfaces, configuration files and error messages; document metadata is descriptive information embedded in files by the software that created them, which may disclose user names, internal file paths, software versions and organisational structure.

Why a search engine knows things you never published

The confusion to clear first: organisations think of their website as the pages they linked, and a search engine's index as a copy of those pages. Neither is quite true.

A crawler follows links, but it also finds content in other ways: a link from somebody else's site, a URL that appeared in a public document, a host name discovered from certificate transparency, or a sitemap listing pages nobody links. So a page can be indexed without ever being linked from the site. "Nobody knows the address" is not a security control, and a page reachable by anyone who knows the URL is, in practice, a public page.

Worse, the index persists. Content removed from a site can remain in a search engine's cache for a while, and in web archives indefinitely. Deleting a page does not un-publish what it said.

What search-engine reconnaissance actually does

The technique uses the advanced operators that search engines provide, which are ordinary documented features intended for legitimate use. In general terms they let a searcher restrict results by:

  • Site or domain, to see everything indexed for an organisation, including subdomains the searcher did not know existed.
  • File type, to find documents rather than pages: spreadsheets, presentations, configuration files, backups, databases.
  • Words in the URL or the title, which is how directory listings and administrative interfaces are located, since both produce characteristic titles.
  • Words in the body, to find pages containing error messages, credentials or internal terminology.

Combining these is what makes it powerful. Restricting to an organisation's domain, to a document file type, and to a word that appears in sensitive documents will surface material the organisation never intended to publish. The practice of building such queries is widely documented and there are public collections of them.

What it typically finds:

  • Directory listings, where a folder with no index page displays its contents, exposing backups, uploads, and files never meant to be reachable.
  • Documents that were uploaded for one recipient and left in a public folder: price lists, internal procedures, staff lists, scanned forms.
  • Configuration and backup files left in the web root, which may contain database credentials.
  • Administrative login pages that were never linked but were indexed.
  • Error messages containing software versions and internal file paths.
  • Old content that still names systems, staff or suppliers.
munotes.in101

Search-Engine Reconnaissance and Document Metadata

All of this is passive by the definition of the earlier chapter: the searcher queries the search engine, not the target, so the target's logs record nothing. That is exactly why it is done first.

Document metadata

The second half of the chapter is the same problem arriving by a different route: information published inside files rather than on pages.

When software creates a document it records descriptive information in the file. Depending on the format and the tool, that can include:

  • the author's name and often their user name on the machine, which reveals the organisation's naming convention for accounts;
  • the organisation name registered in the software;
  • creation and modification times, and the identities of everyone who edited it;
  • the software and version used, which is a technology-profile item;
  • file paths, which disclose internal server names and folder structures, for example a path showing a departmental file server's name;
  • for images, the camera or device, and sometimes location coordinates;
  • in some formats, content that was deleted but not removed, such as text hidden behind a redaction drawn as a shape, or earlier revisions retained in the file.

That last one is the most serious and the least understood. A redaction applied as a black rectangle over text in some document formats hides the text visually while leaving it in the file, so it can be recovered by anyone. Documents have been published in this state by organisations that believed they had removed the information.

An attacker who collects an organisation's published documents and extracts the metadata gains: a list of user names, the account naming convention, internal server and path names, and the software versions in use. Tools to do this in bulk are well known, and the whole operation is passive.

The defences

The two halves share a shape: the information was published by accident, so the control is process rather than technology alone.

For search-engine exposure:

  • The real fix is that sensitive material must not be reachable. If a document requires authorisation, it must be behind authentication, not merely unlinked. A crawler directive asking search engines not to index a page is a request to well-behaved crawlers, not an access control, and it does not stop anyone who has the URL.
  • Disable directory listing, which is a web-server setting and one of the commonest real findings.
  • Keep non-public files out of the web root entirely, including backups, exports and configuration.
  • Use generic error pages in production.
  • Search for your own organisation regularly, using the same operators an attacker would. This is the single most useful action in the chapter, because it finds what is already exposed.
  • Request removal of content that is indexed and should not be, and, because the index reflects the site, remove or protect the underlying content first, or it will simply be re-indexed.
munotes.in102

Search-Engine Reconnaissance and Document Metadata

A caution worth stating plainly: a crawler-exclusion file that lists the paths you do not want indexed is itself readable, so a file listing your sensitive directories is a map for an attacker. Excluding a path is not protecting it.

For document metadata:

  • Strip metadata before publishing. Most office and PDF tools have a document-inspection feature that removes personal and hidden information; for a publishing workflow this should be a required step rather than an optional one.
  • Redact properly. Remove the underlying text, do not cover it. Use the software's redaction feature or flatten the document, and verify by searching the published file for the text that should be gone.
  • Prefer exported formats for publication, since converting often discards revision history and comments.
  • Check images for embedded location and device data.
  • Make it a gate. Since this is an accident, the control must be part of the process that publishes, not a reminder to be careful.

A worked example

Anjali audits her college's published material, entirely passively.

  • Restricting a search to the college domain and to spreadsheet files returns a document listing student names with enrolment numbers, uploaded two years ago to a folder that was never linked. Finding: personal data is publicly retrievable; it is indexed, so the URL is effectively public.
  • A query for the characteristic title of a directory listing, restricted to the domain, returns an open /uploads/ folder containing scanned forms. Finding: directory listing is enabled.
  • Downloading three published PDFs and inspecting their metadata gives four staff user names in the form surname_initial, the internal path \\\\fileserver01\\admin\\, and the version of the software used. Finding: account naming convention, an internal server name and a software version are disclosed.
  • One PDF has a section covered by a black rectangle; selecting the text underneath recovers it. Finding: an improper redaction has published the information it was meant to hide.

Her recommendations: remove the student spreadsheet and treat it as a personal-data incident (not merely a hygiene issue); disable directory listing and move uploads out of the web root; require metadata stripping before publication; re-issue the improperly redacted document and withdraw the original; and add a quarterly self-search using the same queries.

Note that the first and last findings need different responses. Removing the file stops future retrieval but does not undo the disclosure, since it has been indexed and may be cached or archived. Confidentiality, once lost, cannot be restored, which is the point made in the CIA chapter now arriving in a concrete form.

munotes.in103

Search-Engine Reconnaissance and Document Metadata

What beginners get wrong

  • Believing an unlinked page is private. It can be indexed from other sources, and a URL known to anyone is effectively public. Authentication is the control.
  • Using a crawler-exclusion file as protection. It is a request to polite crawlers, it does not restrict access, and the file itself advertises the paths you consider sensitive.
  • Thinking removal undoes exposure. Caches and archives persist, and anything already retrieved is gone. Removal stops the bleeding; it does not heal.
  • Redacting by drawing over text. In many formats the text remains in the file. Redaction must remove the content, and the result should be verified.
  • Treating metadata as trivia. It supplies user names, the account naming convention, internal server paths and software versions, all of which feed later phases.
  • Not searching for yourself. The technique is available to defenders at no cost, and it is the fastest way to find what is already exposed.

Quick revision

  • Search engines index content that was never linked, so "nobody knows the URL" is not a control; indexes and archives also persist after removal.
  • Advanced operators restrict by site, file type, words in the URL or title, and words in the body; combined, they surface directory listings, stray documents, configuration and backup files, unlinked administrative pages and error messages. Querying a search engine is passive.
  • Document metadata can disclose author and user names, the organisation, edit history, software versions, internal file paths, image location data, and text that was hidden rather than removed (improper redaction).
  • Defences: authenticate what must be protected; disable directory listing; keep non-public files out of the web root; generic error pages; search for yourself regularly; strip metadata and redact properly as a required publishing step, not a reminder.
  • A crawler-exclusion file is readable and lists your sensitive paths; excluding is not protecting.

Test yourself

  1. Why can a page an organisation never linked still appear in a search engine, and what follows for security?

Because crawlers find URLs from other sites, public documents, sitemaps and certificate data, so a page can be indexed without being linked. It follows that obscurity of the address is not a control; anything that must be restricted needs authentication.

  1. What does a crawler-exclusion file actually do, and why can it make things worse?

It asks well-behaved crawlers not to index the listed paths; it does not prevent access by anyone who has or guesses the URL. It can make things worse because the file is itself publicly readable, so it advertises exactly which paths the organisation considers sensitive.

munotes.in104

Search-Engine Reconnaissance and Document Metadata

  1. Name four kinds of information document metadata can disclose.

The author's name and machine user name (revealing the account naming convention), the organisation and edit history, the software and version used, and internal file paths and server names; images may also carry device and location data.

  1. Why is drawing a black rectangle over text an unsafe way to redact a document?

Because in many formats the underlying text remains in the file and is merely hidden visually, so it can be selected, copied or extracted by anyone who receives the document. Proper redaction removes the content, and the published file should be verified afterwards.

  1. An indexed spreadsheet of personal data is discovered and removed. Why is the problem not fully solved?

Because the content has already been indexed and may persist in caches and web archives, and anyone who retrieved it retains it. Removal prevents further retrieval from the source but cannot undo the disclosure, which is why confidentiality loss is treated as irreversible and, for personal data, as an incident.

Contents This chapter on its own page

munotes.in105

Chapter Twenty-Three

Reducing Your Own Footprint: the Defensive Audit

Syllabus topic Module 1, "Footprinting and Information Gathering Methodology"; Course Outcome 5, "Recommend appropriate mitigation strategies and security hardening measures"

In one line

Run the whole reconnaissance process against your own organisation, write down what an attacker would learn, and then decide, item by item, whether to remove it, restrict it, or accept it and defend against its use.

In examination wording: a footprint audit is the systematic application of open-source intelligence techniques to one's own organisation in order to determine what information is publicly available to an attacker, to eliminate unnecessary exposure, and to identify assets that were unknown to the organisation's own inventory.

Why the defensive audit is worth more than it sounds

Three reasons, and the third is the one that surprises people.

It is free and lawful. Everything in the passive half of this block can be done about your own organisation without permission from anyone, because it touches nothing. There is no engagement to arrange and no risk to manage.

It finds what an attacker will find. You are not guessing at your exposure; you are measuring it with the attacker's own method.

It routinely discovers assets the organisation did not know it had. This is the finding that justifies the exercise on its own. Certificate transparency logs, search-engine results and registry data regularly reveal hosts, subdomains, cloud services and published documents that appear on no inventory: a test server from a project that ended, a marketing site set up by a department without telling IT, a cloud storage area created for one file transfer. These are the most dangerous assets an organisation owns, because nobody is patching them, nobody is monitoring them, and nobody will notice when they are compromised.

That is why the audit is not a tidy-up exercise. It is an inventory exercise, and inventory is the control that everything else depends on: you cannot patch, monitor, back up or decommission a system you do not know exists.

The audit, as a procedure

A repeatable sequence, using only the passive techniques of the previous chapters.

1. Establish the perimeter of the question. List the domain names the organisation owns, including old ones, misspellings registered defensively, and country variants. This is harder than it sounds and is itself a finding when it proves difficult.

2. Enumerate hosts. From certificate transparency logs for every domain, from public DNS records, from an internet-wide indexing service, and from web archives. Produce a list of every host name you can find.

3. Reconcile against the inventory. Compare the discovered list with the organisation's own asset register. Every host in the first list and not the second is a finding, and the question for each is: what is it, who owns it, is it patched, is it monitored, and should it exist at all?

4. Profile the technology. For each public host, what product and version is disclosed, from headers, page source, error pages and job advertisements? Is each patched?

munotes.in106

Reducing Your Own Footprint: the Defensive Audit

5. Search for stray content. Apply the search-engine techniques to each domain: indexed documents, directory listings, unlinked administrative pages, error messages.

6. Inspect published documents. Sample the documents the organisation publishes and extract their metadata. Check for improper redaction.

7. Review people exposure. The email format, the staff list, technologies named in profiles and talks, and senior staff who are impersonation targets.

8. Check code and secrets. Search public repositories for the organisation's domains and internal names; scan for committed credentials.

9. Check registration data. WHOIS and registry records for exposed personal contact details and, importantly, for domain expiry dates.

10. Write it up as findings with decisions, which is the next section.

The three decisions

For every item found, exactly one of three decisions, and stating them explicitly is what makes the audit a piece of work rather than a list of worries.

Remove it. The item serves no purpose and can go: the forgotten test host is decommissioned, the stray spreadsheet is deleted, the directory listing is disabled, the improperly redacted document is withdrawn and reissued. This is the best outcome and should be used wherever possible, because it eliminates rather than manages.

Restrict it. The item is needed but not by everyone: the administrative interface is moved behind authentication or restricted to an internal network, the document is moved behind a login, the verbose error page is replaced with a generic one for the public and kept in the server-side log.

Accept and defend. The item cannot reasonably be removed, and here the audit's honesty matters. You cannot make your senior staff unfindable, or stop certificates for your host names being published, or prevent the software you run being fingerprinted. For each accepted exposure, name the control that makes it insufficient:

Unavoidable exposureThe control that makes it not matter
Staff names and the email format are discoverableMulti-factor authentication; verification through a second channel for payment changes; training
Host names appear in certificate transparencyEvery host is inventoried, patched and monitored
The software and version can be fingerprintedPatch management, so the version has no unpatched flaw
The public site must be publicly readableNothing sensitive is on it; sensitive material is authenticated
An internet-indexing service records your bannersThe services it records are ones you intend to expose, and they are current

The right-hand column is the whole argument of the module in miniature: since reconnaissance cannot be prevented, security must not depend on it failing. An organisation whose defence is that an attacker will not find out what it runs has no defence at all.

munotes.in107

Reducing Your Own Footprint: the Defensive Audit

What "obscurity is not security" does and does not mean

The slogan is often stated too strongly, and a good answer distinguishes.

It is true that obscurity must not be the control you rely on. A system protected only because its address is unpublished is protected by a fact you do not control and cannot verify, and it fails completely the moment the address leaks, which the earlier chapters showed happens routinely through certificates, archives and indexes.

It is also true that needless disclosure is a gift. Publishing an exact version number, an internal architecture, or a complete staff directory costs the organisation nothing to avoid and saves an attacker real effort. Reducing it is worth doing.

The reconciliation: obscurity is a valid supplementary measure and an invalid primary control. Reduce your footprint because it raises the attacker's cost, and never let anything depend on the reduction having worked.

A worked example, and the journal practical

This is the practical to record in the journal, and it can be done entirely lawfully against your own institution or a system you own.

Meera audits her college. Working only from third-party sources:

  • Hosts. Certificate transparency gives fourteen host names; the college's IT department recognises nine. Five unknown hosts, of which two respond and three do not. One is a results portal from an old academic year still serving pages.
  • Technology. The old portal discloses a web-server version with two published High-severity flaws. The main site suppresses its version.
  • Stray content. A restricted search finds an indexed spreadsheet of student contact details and an open uploads directory.
  • Documents. Metadata from four published PDFs yields the staff account naming convention and an internal file-server name.
  • People. The email format is public; around eighty staff are listed on professional networks.
  • Registration. One secondary domain expires in five weeks with no auto-renewal.

Her findings, with decisions:

FindingDecisionAction
Old results portal, unpatched, unknown to ITRemoveDecommission; if needed, rebuild patched and inventoried
Four other unknown hostsRestrictIdentify owners, add to inventory, patch and monitor
Indexed student spreadsheetRemoveDelete, request de-indexing, treat as a personal-data incident
Open uploads directoryRemoveDisable directory listing; move uploads out of the web root
Metadata disclosing naming conventionRestrictRequire metadata stripping before publication
Email format and staff list publicAccept and defendMulti-factor authentication; phishing training; verification procedure
Secondary domain expiringRestrictEnable auto-renewal; monitor expiry for all domains

The most valuable line is the first, and it was not a vulnerability in the ordinary sense. It was an asset nobody knew about, found by a free, lawful, passive technique. That is what this chapter exists to teach.

munotes.in108

Reducing Your Own Footprint: the Defensive Audit

What beginners get wrong

  • Treating the audit as tidying. Its main product is an inventory correction, and unknown assets are the most dangerous ones.
  • Trying to remove everything. Much exposure is necessary. The discipline is to decide remove, restrict, or accept-and-defend, and to name the control for every acceptance.
  • Relying on obscurity. It is a supplement, never a primary control. Anything that depends on an address staying secret is undefended.
  • Auditing once. Exposure regrows continuously as people publish, provision and leave. It is a recurring exercise, and certificate transparency monitoring makes part of it continuous.
  • Skipping the reconciliation step. Enumerating hosts is only half the work; comparing them with the asset register is where the finding is.
  • Forgetting domain expiry. A lapsed domain can be re-registered by anyone and used to impersonate the organisation.

Quick revision

  • Run reconnaissance against yourself: free, lawful, passive, and it measures your real exposure rather than guessing at it.
  • Procedure: list domains, enumerate hosts (certificate transparency, DNS, indexing services, archives), reconcile against the asset inventory, profile technology, search for stray content, inspect document metadata, review people exposure, check repositories for secrets, check registration and expiry, write findings with decisions.
  • The main product is often an inventory correction: unknown assets are unpatched, unmonitored and the most dangerous the organisation owns.
  • Three decisions per item: remove, restrict, or accept and defend, and every acceptance must name the control that makes the exposure insufficient.
  • Obscurity is a valid supplementary measure and an invalid primary control: reduce the footprint to raise the attacker's cost, but never depend on it.
  • Repeat it; exposure regrows.

Test yourself

  1. What is the most valuable finding a footprint audit typically produces, and why?

Assets the organisation did not know it owned, such as forgotten subdomains, test systems or cloud services. They are the most dangerous assets it has, because nothing unknown is patched, monitored or backed up, and no one will notice its compromise.

  1. State the three decisions available for each item found, and the requirement attached to the third.

Remove it, restrict it, or accept it and defend against its use. Every acceptance must name the specific control that makes the exposure insufficient, such as multi-factor authentication against a discoverable email format, or patch management against a fingerprintable version.

  1. In what sense is "obscurity is not security" true, and in what sense is reducing your footprint still worthwhile?

It is true that obscurity must never be the primary control, since it depends on a fact you neither control nor can verify and fails entirely once the information leaks. Reducing the footprint remains worthwhile because needless specifics cost nothing to withhold and save an attacker real effort, so obscurity is a legitimate supplementary measure.

munotes.in109

Reducing Your Own Footprint: the Defensive Audit

  1. Why must the host-enumeration step be followed by a reconciliation step?

Because the security value lies in the difference between what is discoverable and what the organisation's asset register records. Enumeration alone produces a list; comparing it with the inventory identifies the unknown, unmanaged assets that constitute the real finding.

  1. Why is a footprint audit a recurring exercise rather than a one-off project?

Because exposure regrows continuously as staff publish material and talks, departments provision new hosts and cloud services, certificates are issued, and people join and leave. Parts of it, such as monitoring certificate transparency for your own domains, can be made continuous.

Contents This chapter on its own page

munotes.in110

Chapter Twenty-Four

How the Domain Name System Resolves a Name

Syllabus topic Module 1, "DNS Enumeration and Domain Intelligence: Study DNS structure"

In one line

The DNS is a distributed, hierarchical directory that turns names people can remember into the addresses machines use. It answers anyone who asks, it caches aggressively, and it was designed without authentication, which is the root of several later attacks.

In examination wording: the Domain Name System is a hierarchical, distributed naming system that maps domain names to IP addresses and other resource records; resolution proceeds from the root servers through top-level domain servers to the authoritative name server for a zone; answers are cached for a period controlled by each record's time to live.

Why security people study the DNS so closely

Three reasons, and they run through the rest of this book.

It is a map. An organisation's DNS records describe its infrastructure: where its websites live, who handles its mail, which cloud services it uses, what its host names are called. Reading that map is the subject of the next three chapters.

It is public by design. Your mail server must be findable or nobody can send you mail. So the DNS answers strangers, and much of reading it never touches your systems at all.

It was built without authentication. The original protocol has no way for a client to verify that an answer came from the right server or was not altered in transit. Everything in DNS spoofing, cache poisoning and a good deal of man-in-the-middle work follows from that single design fact, and the later chapters on those attacks assume this one.

The hierarchy

A domain name is read right to left, and each part is a level in a tree.

Take results.college.test:

  • . (the implied dot at the end) is the root.
  • test is the top-level domain (TLD).
  • college is the domain registered under that TLD.
  • results is a subdomain, and may itself have subdomains.

The tree is divided into zones. A zone is a portion of the namespace that one administrator is responsible for, and the boundary is where authority is delegated. The operators of .test do not know or care what records exist inside college.test; they only know which name servers to point to. That delegation is what makes the system scale to the whole internet: no server needs to know everything, only who to ask next.

The parts that do the work

The stub resolver is the small piece of code in your operating system that applications use. It does almost nothing itself; it asks a recursive resolver.

The recursive resolver (your internet provider's, your organisation's, or a public one) does the actual work of finding the answer, and it caches what it learns. Most queries most of the time are answered from its cache without troubling anyone else.

munotes.in111

How the Domain Name System Resolves a Name

Root servers know one thing: which servers are authoritative for each top-level domain. They are a small, globally distributed set of addresses that every resolver knows in advance, and they answer with referrals rather than final answers.

TLD servers know which name servers are authoritative for each domain registered under them.

Authoritative name servers hold the actual records for a zone. They are the source of truth, and an organisation either runs them or, more often, pays a provider to.

A resolution, step by step

Your browser needs the address of results.college.test and nothing is cached anywhere.

  1. The stub resolver asks the configured recursive resolver: "what is the address of results.college.test?"
  2. The resolver has nothing cached, so it asks a root server. The root does not know, but it knows who handles .test, and returns a referral naming those servers.
  3. The resolver asks a .test TLD server. It does not know the address either, but it knows college.test is delegated to particular name servers, and returns that referral.
  4. The resolver asks one of college.test's authoritative name servers. This one knows, and returns the answer: the A record with the address.
  5. The resolver caches the answer for the record's time to live, and returns it to the stub resolver, which gives it to the browser.

Two names for the two behaviours: the resolver performed a recursive query on your behalf (it took responsibility for finding the final answer), while its own queries to the root and TLD servers were iterative (each returned a referral rather than chasing it further). Authoritative servers normally refuse to act recursively for strangers, which matters later: a server that will, an open resolver, can be abused for amplification in denial-of-service attacks.

Caching and the time to live

Every record carries a time to live (TTL), a number of seconds for which a resolver may keep the answer. Caching is what makes the DNS fast and keeps the root servers from collapsing under the world's traffic.

For a security reader, three consequences:

A cached wrong answer persists. If an attacker succeeds in getting a resolver to cache a false record, that falsehood is served to every user of that resolver until the TTL expires. This is cache poisoning, and the damage is multiplied by the number of people using that resolver and by the TTL.

Change takes time to propagate. If you must move a service or, worse, respond to an incident by changing a record, users continue to receive the old answer until caches expire. Administrators therefore lower the TTL in advance of a planned change. In an incident, a long TTL is an obstacle.

munotes.in112

How the Domain Name System Resolves a Name

Querying a cache is not querying the target. This is the passive/active line from the reconnaissance chapter, now explained: asking a public recursive resolver usually returns a cached answer, so the target's authoritative servers never see you. Asking the authoritative server directly does reach the target's machine, and is active.

The query itself, and where it is weak

A DNS query is small, and historically it is sent over UDP, a connectionless protocol with no handshake. That choice is the source of two weaknesses worth naming now because later chapters rely on them.

There is no authentication. A client asking a question accepts the first plausible answer that arrives. The original protocol's only checks that an answer belongs to a question are that it comes from the expected address and port and carries a matching 16-bit transaction identifier. An attacker who can guess or observe those can forge a reply, which is the basis of DNS spoofing and cache poisoning.

The source address can be forged. Because UDP has no handshake, an attacker can send a query claiming to come from a victim's address, and the response goes to the victim. Since responses can be much larger than queries, this gives amplification, which the denial-of-service chapter uses.

Both are addressed, partially, by later additions: DNSSEC signs records cryptographically so a forged answer can be detected, and encrypted DNS (over TLS or HTTPS) protects the query in transit from a local attacker. Neither is universal, and the reasons are discussed in the hardening chapter.

A worked example, read as reconnaissance

Karan looks up his own college's records using a public resolver, which is passive.

  • college.test returns an A record pointing to an address. Querying the registry for that address shows it belongs to a hosting provider, so the site is hosted, not self-run.
  • The NS records name two servers at a DNS provider, so the DNS is outsourced, and those servers are not the college's own to secure.
  • The MX records point to a well-known cloud mail provider, so staff mail is there, which tells an attacker exactly which provider's login page a phishing message should imitate.
  • A TXT record contains an SPF policy listing four systems permitted to send mail as the college, which is a partial inventory of its sending infrastructure.
  • The TTL on the main A record is 300 seconds, which is short and suggests the administrators expect to change it.

Every one of those was answered from a cache and none reached the college's servers. Karan has learned the hosting arrangement, the DNS provider, the mail provider and part of the sending infrastructure without touching anything, which is why the reconnaissance chapter called DNS one of the richest passive sources.

munotes.in113

How the Domain Name System Resolves a Name

What beginners get wrong

  • Thinking the DNS only maps names to addresses. It carries mail routing, policy records, service discovery and verification tokens, and those are often more revealing than the addresses.
  • Confusing recursive with iterative. The resolver answers your query recursively; the servers it consults answer iteratively with referrals.
  • Ignoring the TTL. It governs how long a poisoned answer persists and how quickly a legitimate change or an incident response takes effect.
  • Assuming any DNS lookup is passive. Querying a public resolver usually is; querying the target's authoritative server directly is not, because it reaches their machine.
  • Forgetting that the protocol has no authentication. This is not a bug to be patched but a design property, and it is why DNSSEC exists and why several later attacks are possible at all.
  • Believing the root servers know everything. They know only which servers handle each top-level domain, and answer with referrals.

Quick revision

  • Names are read right to left: root, TLD, domain, subdomain. The namespace is divided into zones, and delegation between them is what lets the system scale.
  • Parts: stub resolver (in the client), recursive resolver (does the work, caches), root servers (refer to TLDs), TLD servers (refer to domains), authoritative name servers (hold the truth).
  • Resolution: stub asks resolver; resolver asks root, then TLD, then authoritative, following referrals; answer cached and returned. The resolver's own queries are iterative; the query it answers for you is recursive.
  • TTL controls caching: a poisoned answer persists for its duration, changes propagate only as caches expire, and short TTLs are set before planned changes.
  • Querying a cache is passive; querying the authoritative server is active.
  • The protocol has no authentication and uses UDP, giving rise to spoofing and cache poisoning, and to source-address forgery and amplification. DNSSEC and encrypted DNS address parts of this.

Test yourself

  1. Describe the resolution of a name from a cold cache, naming each server consulted.

The stub resolver asks the recursive resolver, which asks a root server and receives a referral to the top-level domain's servers, asks one of those and receives a referral to the domain's authoritative name servers, then asks an authoritative server, which returns the record. The resolver caches the answer for its TTL and returns it.

  1. What is the difference between a recursive and an iterative query?

In a recursive query the server asked takes responsibility for obtaining the final answer, which is what a resolver does for a client. In an iterative query the server returns the best it has, usually a referral to another server, which is how root and TLD servers respond.

munotes.in114

How the Domain Name System Resolves a Name

  1. Give two security consequences of DNS caching.

A falsified record that a resolver accepts is served to all of that resolver's users until the TTL expires, multiplying the harm of cache poisoning; and legitimate changes, including emergency ones during an incident, do not take effect for clients until cached copies expire, which is why administrators lower the TTL before planned changes.

  1. Why is querying a public resolver passive reconnaissance while querying the authoritative server is active?

Because the public resolver usually answers from its own cache, so the target's servers never receive a query and their logs record nothing. Querying the authoritative name server sends a packet to a machine the target operates, which is an interaction with their system and is recorded.

  1. Which design property of the original DNS protocol underlies spoofing and amplification attacks?

The absence of authentication, combined with the use of connectionless UDP. A client accepts the first plausible reply matching the expected address, port and transaction identifier, which allows forged answers; and because there is no handshake, a query's source address can be forged so that a larger response is directed at a victim.

Contents This chapter on its own page

munotes.in115

Chapter Twenty-Five

The Record Types, and What Each One Reveals

Syllabus topic Module 1, "DNS Enumeration and Domain Intelligence: ... record types (A, MX, NS, TXT, CNAME)"

In one line

Each record type answers a different question about a domain, and each therefore leaks a different piece of the infrastructure: A where a host is, MX who handles the mail, NS who runs the DNS, CNAME which third party is really behind a name, and TXT which services the organisation uses.

In examination wording: DNS resource records are typed entries in a zone; the principal types are A (IPv4 address), AAAA (IPv6 address), MX (mail exchange), NS (name server), CNAME (canonical name alias), TXT (arbitrary text, used for policy and verification), SOA (start of authority), PTR (reverse mapping) and SRV (service location).

A and AAAA: where the host is

What they are for. An A record maps a name to an IPv4 address; AAAA does the same for IPv6. These are the records that make the web work.

What they reveal. The address itself, and therefore, through a registry lookup, who hosts it. An address inside a cloud provider's range says the service is in that provider; an address in the organisation's own allocated range says they host it themselves, and that the neighbouring addresses are probably theirs too, which is the start of infrastructure mapping.

Two practical notes. A name may have several A records, used for load distribution, so one lookup can reveal several servers. And IPv6 is frequently forgotten: an organisation that carefully firewalls its IPv4 addresses may have an AAAA record pointing at a host with no equivalent IPv6 filtering, which is a real and recurring finding. Always check both.

MX: who handles the mail

What it is for. An MX record names the mail servers that accept mail for the domain, each with a preference number; lower numbers are tried first, which gives redundancy.

What it reveals. This is a high-value record for an attacker and the reason is not the address. MX records usually name a mail provider, and knowing which provider an organisation uses tells a phisher exactly which login page to imitate, which branding to copy, and which security features to expect. A convincing phishing message is much easier to write when you know the target sees that provider's interface every day.

It also reveals whether mail is filtered by a security service, since many organisations point their MX at a filtering provider that scans mail before passing it on. An attacker learns from this what their message must survive.

NS: who runs the DNS

What it is for. NS records name the authoritative name servers for the zone. They appear both in the parent zone, as the delegation, and inside the zone itself.

What it reveals. Whether DNS is outsourced or self-hosted, and to whom. Both matter:

munotes.in116

The Record Types, and What Each One Reveals

  • Self-hosted means the name servers are the organisation's own machines, which are therefore targets, and must be patched and monitored like any other server.
  • Outsourced means the security of the organisation's entire naming depends on an account at a provider. That account is a high-value target, because whoever controls it can repoint every name the organisation owns, and it should be protected with multi-factor authentication and registrar locking.

A mismatch between the NS records at the parent and those in the zone is a misconfiguration worth reporting; it causes intermittent failures and suggests the zone is not well maintained.

CNAME: the alias that points elsewhere

What it is for. A CNAME makes one name an alias for another. Asking for the alias returns the canonical name, which is then resolved.

What it reveals. That a service is really run somewhere else. shop.company.test as a CNAME to a hosting platform, status.company.test to a status-page provider, mail.company.test to a mail provider: each one names a third party the organisation depends on. For an attacker that is a list of suppliers to consider attacking instead, and a list of brands to impersonate.

It also introduces a specific and well-known risk. If a CNAME points to a service the organisation no longer uses, and that service allows anyone to claim the name, an attacker can register it and take control of content served at the organisation's own host name. This is called a dangling CNAME or subdomain takeover, and it is a common finding precisely because decommissioning a service and removing its DNS record are two separate tasks and the second is often forgotten. The defence is straightforward: remove the DNS record when you stop using the service, and audit for CNAMEs pointing at nothing.

TXT: the quiet prize

What it is for. A TXT record holds arbitrary text. Because it was the only flexible record available, it became the place where everything else is put.

What it reveals, and this is the richest single record type:

SPF (Sender Policy Framework). A TXT record listing every server permitted to send mail as the domain. Read as reconnaissance, it is a published list of the organisation's sending infrastructure: its mail provider, its marketing platform, its ticketing system, its payroll service, anything that sends mail on its behalf. An attacker learns the organisation's suppliers from one record. It frequently also reveals systems nobody remembers, a marketing tool from a campaign three years ago still authorised to send as the domain, which is both an intelligence gift and a genuine security weakness.

DMARC, published at a conventional subdomain as a TXT record, states what a receiver should do with mail that fails authentication, and where to send reports. Read as reconnaissance, its policy setting tells an attacker whether forged mail from this domain will be rejected, quarantined or merely monitored, which is to say whether a domain-spoofing phishing attempt is likely to be delivered. A policy of "none" is an invitation.

munotes.in117

The Record Types, and What Each One Reveals

Domain verification tokens. Cloud services routinely ask an organisation to publish a TXT record to prove control of the domain. The tokens are recognisable, so the set of them is a list of the cloud services the organisation has signed up to, often including services the security team does not know about.

Other policy records. DKIM public keys (at their own selector subdomains) and various service-specific records.

The defensive reading: you cannot hide these, because their purpose requires them to be readable by strangers. What you can do is keep them accurate (remove sending systems you no longer use), set a strict DMARC policy, and recognise that the verification tokens are an inventory of your cloud estate that an auditor should reconcile.

SOA, PTR and SRV

SOA (Start of Authority) appears once per zone and holds administrative parameters: the primary name server, an administrative contact address, a serial number the secondaries use to detect changes, and timing values. It reveals an administrative email address, which is a person to target, and the serial number, which by convention often encodes a date, telling an attacker when the zone was last changed.

PTR maps an address back to a name, the reverse of an A record, and lives in a special reverse zone controlled by whoever holds the address range. Reverse lookups across an organisation's address range often produce a list of host names, sometimes descriptive ones (backup01, test-db), which is why reverse-DNS sweeps are a standard enumeration step.

SRV records locate a service by protocol and name, giving host and port. Where they are used, they advertise which services exist and on what ports, which is unusually helpful to an attacker.

A worked example: reading a zone

Sana examines her own organisation's records through a public resolver.

RecordValue observedWhat she concludes
Aan address in a cloud provider's rangethe website is hosted, not self-run
AAAApresent, pointing to the same servicecheck IPv6 filtering matches IPv4
NStwo servers at a DNS providerDNS is outsourced; that account is a critical asset
MXa well-known mail provider, with a filtering service in frontphishing will imitate that provider and must survive that filter
CNAME on docs.points to a documentation platforma third-party dependency; check it is still in use
TXT (SPF)lists five senders, one unrecognisedan unused sender is still authorised: remove it
TXT (DMARC)policy set to noneforged mail will be delivered: tighten the policy
TXTthree verification tokensthree cloud services, one unknown to the security team
SOAadministrative address, serial suggesting a recent changea contact to protect from targeting
munotes.in118

The Record Types, and What Each One Reveals

Her findings are almost all configuration hygiene, and two are serious: the DMARC policy of none, which leaves the domain spoofable, and the stale SPF entry, which authorises a system nobody controls any more. Neither required touching a single one of the organisation's servers.

What beginners get wrong

  • Treating TXT as unimportant because it is "just text". It carries SPF, DMARC, DKIM and verification tokens, and is the most revealing record type.
  • Forgetting AAAA. IPv6 is frequently unfiltered where IPv4 is carefully controlled. Enumerate both.
  • Ignoring dangling CNAMEs. A CNAME to a service you no longer use can allow an attacker to claim the name and serve content from your host name.
  • Reading NS as trivia. It identifies either servers to attack or a provider account whose compromise repoints everything the organisation owns.
  • Overlooking what MX gives a phisher. Not the address, but the identity of the mail provider to imitate.
  • Leaving stale SPF entries. They publish your suppliers and authorise systems you no longer control to send as you.

Quick revision

  • A / AAAA: the host's address; reveals the hosting arrangement and neighbouring estate. Check IPv6 filtering separately.
  • MX: mail servers with preferences; reveals the mail provider to imitate and any filtering service.
  • NS: authoritative name servers; reveals self-hosted (targets) or outsourced (a provider account that must have multi-factor authentication and registrar locking).
  • CNAME: an alias; reveals third-party dependencies, and a dangling CNAME enables subdomain takeover.
  • TXT: the richest. SPF publishes the sending infrastructure (and stale entries); DMARC reveals whether forged mail is rejected; verification tokens list the cloud services in use.
  • SOA: administrative contact and a serial number often encoding a date. PTR: reverse lookups yield host names. SRV: advertises services and ports.

Test yourself

  1. What do A, MX, NS, CNAME and TXT each map, and give one thing each reveals to an attacker.

A maps a name to an IPv4 address, revealing the hosting arrangement; MX names the mail servers, revealing the mail provider to imitate in phishing; NS names the authoritative name servers, revealing whether DNS is self-hosted or outsourced and to whom; CNAME aliases one name to another, revealing third-party dependencies; TXT holds arbitrary text and reveals sending infrastructure through SPF, spoofing resistance through DMARC, and cloud services through verification tokens.

  1. Why is the TXT record the most revealing type?

Because it carries SPF, which lists every system authorised to send mail as the domain and therefore names the organisation's suppliers; DMARC, whose policy tells an attacker whether forged mail will be delivered; and cloud-service verification tokens, which amount to an inventory of the services the organisation has signed up to.

munotes.in119

The Record Types, and What Each One Reveals

  1. What is a dangling CNAME and why is it dangerous?

A CNAME that still points at a third-party service the organisation no longer uses. If that service lets anyone claim the unused name, an attacker can register it and serve their own content from the organisation's host name, which is a subdomain takeover. It arises because decommissioning a service and deleting its DNS record are separate tasks.

  1. Why must AAAA records be checked separately during an assessment?

Because IPv6 filtering is commonly overlooked. An organisation may firewall its IPv4 addresses carefully while the same service is reachable over IPv6 with no equivalent controls, so enumerating only A records understates the exposure.

  1. What does a DMARC policy of "none" tell an attacker, and what should a defender do?

That mail forged to appear as coming from the domain will still be delivered rather than quarantined or rejected, so domain-spoofing phishing is likely to reach recipients. The defender should move the policy toward quarantine and then reject, once SPF and DKIM alignment has been verified using the reports.

Contents This chapter on its own page

munotes.in120

Chapter Twenty-Six

Subdomain Enumeration and Infrastructure Mapping

Syllabus topic Module 1, "DNS Enumeration and Domain Intelligence: ... to understand infrastructure mapping"

In one line

The prize in DNS work is the list of host names, because each one is a system, and the interesting ones are always the neglected ones: test, staging, old, backup, dev.

In examination wording: subdomain enumeration is the discovery of host names within a domain, and infrastructure mapping is the assembly of those names, their addresses and their address ranges into a model of the organisation's internet-facing estate; it may be performed passively from third-party sources or actively by querying the target's own name servers.

Why the neglected host is the objective

An organisation's main website is usually its best-defended system. It is public, it matters commercially, and somebody is responsible for it. That is precisely why an attacker is not very interested in it.

What they want is the host that nobody owns. A test portal from a project that finished two years ago. A staging copy of the application with real data and no rate limiting. An old marketing site on an unpatched content management system. A departmental server set up without telling IT.

Such hosts share a fatal combination of properties:

  • They run older software, because nobody patches what nobody remembers.
  • They are unmonitored, so an intrusion raises no alert.
  • They often hold real data, because staging environments are routinely populated with copies of production.
  • They sit inside the network, so compromising one is frequently a route to everything else.
  • They are unowned, so even after discovery nobody is sure whether they can be switched off.

Finding them is therefore the single most productive activity in reconnaissance, for an attacker and equally for the defender doing the audit from the previous block.

Passive enumeration: finding names without asking the target

These methods learn host names from third parties, so the target's servers never see the query. They are lawful to perform about any organisation and they are where a professional starts.

Certificate transparency logs. Introduced in the technology chapter and repeated here because for this purpose it is the best source there is. Every certificate a public authority issues is published in an append-only log, and the record names every host the certificate covers. An organisation that obtained a certificate for staging.company.test has published that name to the world permanently. It cannot be opted out of, and it routinely reveals internal-sounding names that appear nowhere else.

Search engines and archives. Indexed pages on subdomains, and archived copies of pages that referenced hosts since removed.

Internet-wide scanning services. Third parties that continuously scan and index the internet, recording which addresses respond and what certificates and banners they present. Querying their data is passive from the target's point of view because the service did the scanning.

munotes.in121

Subdomain Enumeration and Infrastructure Mapping

Public code repositories and documents. Configuration files, scripts and published documents frequently name internal hosts.

Passive DNS. Services that record DNS answers observed across the internet over time and let you query the history of a domain. This can reveal names that existed in the past and addresses a name previously pointed to, which is useful for finding infrastructure that has moved but not been decommissioned.

The organisation's own records. SPF entries name sending systems; MX and NS name providers; and the SOA gives an administrative contact.

Active enumeration: asking the target

These touch the target's name servers and therefore require authorisation.

Zone transfer. If misconfigured to permit it, a single request returns the entire zone. It is the next chapter's subject.

Brute-force (dictionary) enumeration. Ask the target's name servers about a long list of likely names, www, mail, vpn, test, dev, staging, api, admin, backup, and record which resolve. It is effective, it finds names no passive source knows, and it is noisy: the target's DNS servers receive a large number of queries for names that do not exist, which is a distinctive and detectable pattern.

Permutation and alteration. Having found api.company.test, try api-dev, api2, api-staging, and so on. Organisations name things predictably, and this exploits that.

Reverse lookups across the address range. Once the organisation's allocated range is known from registry data, ask for the PTR record of each address. Where reverse DNS is populated, this yields host names directly, often descriptive ones.

A note on wildcards. Some zones answer every possible name with the same address, which makes naive brute-force enumeration report thousands of non-existent hosts. Recognising a wildcard (by querying a name that certainly does not exist and seeing whether it resolves) is a necessary step before trusting brute-force results.

From names to a map

Names alone are a list. Infrastructure mapping turns them into a model, and the steps are mechanical:

  1. Resolve each name to its addresses, both A and AAAA.
  2. Group by address. Several names on one address usually means virtual hosting, and one compromise reaches all of them.
  3. Look up each address at the regional registry (the next chapter) to find who owns it and what the allocated range is. Addresses inside the organisation's own range are self-hosted; addresses in a provider's range are not, and the client cannot authorise testing of the provider.
  4. Sweep the organisation's own ranges for further hosts that have no name at all, which exist more often than people expect.
  5. Classify by apparent purpose from the names: production, staging, development, administrative, infrastructure.
  6. Reconcile against the asset inventory, which is where the finding is.
munotes.in122

Subdomain Enumeration and Infrastructure Mapping

That last step is the point of the whole exercise. A list of forty hosts is data. "Forty hosts exist and the organisation's register lists thirty-one, and of the nine unaccounted for, two are serving pages on outdated software" is a finding, and it is the one that gets acted on.

A worked example

Rahul audits his employer's estate, beginning passively.

  • Certificate transparency for the domain returns twenty-three distinct host names.
  • Passive DNS adds four more that no longer resolve but did within the last year.
  • A scanning service's index confirms which of the twenty-three currently respond, and on which ports, without Rahul sending anything to the company.
  • The SPF record names two sending systems not in the host list, one of them a marketing platform.

Now, and only because the engagement authorises it, he moves to active work:

  • Brute-force enumeration against the company's name servers adds six names the passive sources missed, including jenkins and vpn-old. He first confirms there is no wildcard.
  • Reverse lookups across the company's allocated range reveal four hosts with names but no forward record anybody had listed.

He resolves everything, groups by address, and reconciles:

DiscoveredOn the asset registerFinding
33 live host names249 unaccounted for
vpn-old respondingnoan old VPN endpoint, unpatched, high risk
jenkins respondingnoa build server exposed to the internet
staging responding, with real-looking datanoproduction data in an unmonitored environment
4 hosts in range with no forward DNSnounknown purpose, unowned
marketing platform in SPFnoa supplier with authority to send as the company

The report's headline is not "we found thirty-three hosts". It is "nine internet-facing systems are outside the asset register, two of them serious", and the first recommendation is not a technical control but an ownership process: every host must have a named owner and appear on the register, or be decommissioned.

The defensive answer

Since names cannot be hidden, the defence is ownership and lifecycle rather than secrecy.

  • Maintain an authoritative inventory of every host, with an owner, and reconcile it against certificate transparency and DNS regularly. The audit makes itself continuous if you monitor the logs.
  • Decommission properly. Turning a server off is not decommissioning; the DNS record must be removed too, or you have created a dangling record.
  • Do not put real data in non-production environments. If staging must have realistic data, it must be anonymised, and staging must be protected as production is.
  • Restrict non-production environments to internal networks or authenticated access. A staging system does not need to be reachable by the internet.
  • Monitor your name servers for the pattern of brute-force enumeration: a high rate of queries for names that do not exist.
  • Name things blandly. This is the one place obscurity is cheap: svc-14 tells an attacker less than jenkins-prod. It is a supplementary measure and no substitute for the inventory.
munotes.in123

Subdomain Enumeration and Infrastructure Mapping

What beginners get wrong

  • Thinking the goal is a long list. The goal is the difference between the list and the inventory. Length without reconciliation is not a finding.
  • Starting with brute force. Passive sources are free, lawful, silent, and frequently more complete. Exhaust them first.
  • Forgetting the wildcard check. A wildcard makes every guessed name resolve, and an unwary enumeration reports thousands of phantom hosts.
  • Ignoring names that no longer resolve. Passive DNS history points at infrastructure that may still exist without a name.
  • Assuming a discovered host is in scope. It is not, until the scope says so. This is the discovery rule from the authorisation chapter, and it is where enumeration most often goes wrong professionally.
  • Treating staging as unimportant. It often holds production data and is the least defended thing the organisation runs.

Quick revision

  • The objective is the neglected host (test, staging, old, backup, dev): older software, unmonitored, often real data, inside the network, unowned.
  • Passive: certificate transparency (best single source, cannot be opted out of), search engines and archives, internet-wide scanning services, public repositories and documents, passive DNS history, and the organisation's own SPF, MX and NS records.
  • Active (needs authorisation): zone transfer, brute-force and permutation against the target's name servers (noisy and detectable), reverse lookups across the address range. Check for a wildcard first.
  • Mapping: resolve names, group by address, look up registry ownership and ranges, sweep the ranges, classify by purpose, and reconcile against the asset inventory, which is where the finding lives.
  • Defence is ownership and lifecycle: an authoritative inventory with named owners, proper decommissioning including DNS, no real data in staging, non-production kept off the internet, monitoring for enumeration, and bland naming as a supplement.

Test yourself

  1. Why is a forgotten subdomain more valuable to an attacker than the main website?

Because the main site is defended, monitored and owned, whereas a forgotten host runs older unpatched software, is unmonitored so intrusion raises no alert, frequently holds copies of real data, sits inside the network, and has no owner to notice or respond.

  1. Name three passive sources of host names and say why passive methods are preferred first.

Certificate transparency logs, passive DNS history, and internet-wide scanning services (also search engines, archives, public repositories and the organisation's own SPF records). They are preferred because they are free, lawful about any organisation, silent so the target sees nothing, and often more complete than guessing.

munotes.in124

Subdomain Enumeration and Infrastructure Mapping

  1. What must be checked before trusting brute-force subdomain results, and why?

Whether the zone uses a wildcard, by querying a name that certainly does not exist. If a wildcard answers every name, brute-force enumeration will report large numbers of hosts that do not exist.

  1. What turns a list of discovered hosts into a security finding?

Reconciliation against the organisation's asset inventory. The finding is the set of internet-facing systems that are discoverable but unregistered and therefore unowned, unpatched and unmonitored, not the raw count of hosts.

  1. Why is switching off a server insufficient as decommissioning?

Because the DNS record remains. That leaves a dangling record which may later resolve to an address or a third-party service that somebody else can claim, allowing an attacker to serve content from the organisation's own host name.

Contents This chapter on its own page

munotes.in125

Chapter Twenty-Seven

Zone Transfers and DNS Hardening

Syllabus topic Module 1, "DNS Enumeration and Domain Intelligence"

In one line

A zone transfer is the legitimate mechanism by which one name server copies a zone to another. If it is left open to everyone, it hands an attacker every record in one request, and the fix is a single configuration line.

In examination wording: a zone transfer is the replication of a DNS zone's records from a primary to a secondary name server; where a server is configured to permit transfers to arbitrary hosts, any party may obtain the complete set of records for the zone, disclosing all host names and the infrastructure they describe.

What a zone transfer is for

An organisation runs more than one authoritative name server, so that the loss of one does not make its whole estate unreachable. Those servers must hold the same records.

The mechanism is replication. One server is the primary, holding the master copy; the others are secondaries. The SOA record's serial number is a version marker: each time the zone changes the administrator increases it. Secondaries periodically check the primary's serial, and if it is higher than their copy they request a transfer.

Two kinds exist. A full transfer (AXFR) sends the entire zone; an incremental transfer (IXFR) sends only the changes since the secondary's serial. Both are ordinary, necessary operations, and they run over TCP rather than UDP because a zone can be large.

So the mechanism is not a flaw. It is infrastructure doing exactly what it should, between servers that are supposed to be talking to each other.

What goes wrong

The failure is an access-control failure. The server must decide who may request a transfer, and the correct answer is a short list: this zone's secondaries, and nobody else.

When a server is configured to allow transfers from any host, an attacker simply asks, and receives the complete zone: every A record, every CNAME with its third-party targets, every MX, every TXT with its SPF list, every internal-sounding name the organisation ever created.

The consequence is that the entire previous chapter becomes unnecessary. Certificate transparency, passive DNS, brute-force guessing, reverse sweeps: all of that laborious enumeration is replaced by one request that returns an authoritative and complete answer, including names that no passive source knows and that no dictionary would guess. It is the difference between reconstructing a map from fragments and being handed the map.

It is also active reconnaissance: the request goes to the organisation's own name server and is recorded there, so it requires authorisation.

Why it persists

Students reasonably ask why a misconfiguration with such an obvious fix is still found. Three reasons, and they generalise beyond DNS:

  • Defaults changed but deployments did not. Modern name server software refuses transfers by default, but long-lived servers configured years ago retain permissive settings, and nobody revisits working configuration.
  • It is invisible when it works. An open transfer causes no symptom. Nothing breaks, no user complains, no monitoring alerts. Misconfigurations that produce no symptom survive indefinitely.
  • The secondary list changes. An administrator adding a new secondary under time pressure may widen the permission rather than add one address, intending to tighten it later.
munotes.in126

Zone Transfers and DNS Hardening

The lesson is the general one about configuration: a setting that is wrong but harmless-looking will not be found by operations, only by an assessment.

The fix, and the rest of DNS hardening

Restrict zone transfers to the known secondary servers by address, and where the software supports it authenticate them with a shared key (TSIG), which ties the permission to a cryptographic secret rather than to an address that can be spoofed. This is the single highest-value line in the chapter and it takes minutes.

The rest of the hardening list, which closes the DNS block:

Separate the roles. An authoritative server answers for your zones to the world. A recursive resolver answers queries for your users. They should not be the same machine, and the recursive resolver must not be reachable from the internet. A resolver that answers strangers is an open resolver, and it will be conscripted into amplification attacks against other people, as the denial-of-service chapter explains.

Protect the registrar account. This is the control people forget, and it outranks almost everything else on this list. Whoever controls the registrar account can repoint every name the organisation owns: the website, the mail, everything. Protect it with multi-factor authentication, restrict who can access it, and enable registrar lock, which prevents transfers of the domain to another registrar without a deliberate unlock step. A domain hijack through a registrar account is far more damaging than most compromises, because it redirects the organisation's identity rather than breaching one system.

Watch domain expiry. Enable auto-renewal and monitor expiry dates for every domain, including ones nobody uses. A lapsed domain can be registered by anyone and used to impersonate the organisation or to receive its mail.

Keep records accurate. Remove records for decommissioned services, which prevents the dangling-CNAME takeover of the record-types chapter; prune stale SPF entries; and remove old hosts.

Consider DNSSEC. DNSSEC signs records cryptographically so that a resolver can verify an answer genuinely came from the zone's owner and was not altered. It addresses the authentication gap identified in the resolution chapter, and it is the defence against cache poisoning and spoofed answers. It is not universal because it adds operational complexity, key management and a real risk of taking a domain offline through a signing error, and because validation must be performed by the resolver, which not all are. It is the right answer for a domain whose integrity matters, and the honest summary is that it protects the integrity of answers, not their confidentiality.

munotes.in127

Zone Transfers and DNS Hardening

Consider encrypted DNS (DNS over TLS or over HTTPS) for your own users' queries, which stops a local attacker reading or tampering with lookups on the network. Note the complementary roles: DNSSEC authenticates the data, encrypted DNS protects the channel; neither replaces the other.

Log and monitor. Query logs on the resolver reveal internal hosts contacting suspicious domains, which is one of the best detective controls an organisation has, and it belongs to the defender's-mirror chapter. On the authoritative side, monitor for the enumeration pattern: many queries for names that do not exist.

Rate limit responses on authoritative servers, which reduces their usefulness as amplifiers.

A worked example

An assessor reviews an organisation's DNS, within scope.

  • She first confirms the basics passively: NS records name two servers, both operated by the organisation itself rather than a provider.
  • With authorisation, she requests a zone transfer from each. The first refuses. The second succeeds, returning 61 records.
  • The transfer reveals 38 host names, of which the passive enumeration of the previous chapter had found 22. The new ones include vpn-legacy, hr-test and backup-dr.
  • It also reveals a CNAME pointing to a cloud storage service that returns an error, suggesting the service was decommissioned but the record was not: a possible subdomain takeover.
  • Reviewing the configuration with the administrators shows the second server permits transfers from any address, because it was rebuilt last year and the restriction was not carried across.

Her findings, in priority order:

  1. Open zone transfer on the second name server. Restrict to the known secondaries and authenticate with TSIG. This is urgent and takes minutes.
  2. Dangling CNAME to a decommissioned service. Remove the record and check for others.
  3. Sixteen host names not on the asset register, discovered through the transfer, several suggesting unmaintained systems.
  4. The registrar account lacks multi-factor authentication and registrar lock is not enabled.
  5. Recommendations: separate authoritative from recursive, enable auto-renewal and expiry monitoring, and evaluate DNSSEC.

Note that the open transfer's real damage was not the transfer itself but what it revealed: sixteen unmanaged systems. The configuration error was a minute's work to fix; the inventory problem it exposed is months of work, and is the more important finding.

What beginners get wrong

  • Calling the zone transfer an attack. It is a legitimate replication mechanism. The defect is an access-control setting, and describing it correctly is what makes the fix obvious.
  • Thinking an open transfer is rare because the fix is easy. It persists because it causes no symptom, so operations never discovers it.
  • Testing for it without authorisation. The request reaches the organisation's server and is recorded; it is active reconnaissance.
  • Believing DNSSEC encrypts DNS. It authenticates records and protects integrity; it does not provide confidentiality. Encrypted DNS is the separate control for the channel.
  • Ignoring the registrar account. It is the highest-leverage target in the whole DNS estate, since it repoints everything at once, and it is often protected only by a password.
  • Running one server for both authoritative and recursive roles. An internet-reachable recursive resolver becomes an amplifier used against third parties.
munotes.in128

Zone Transfers and DNS Hardening

Quick revision

  • A zone transfer replicates a zone from primary to secondary; AXFR is full, IXFR incremental, and the SOA serial signals a change. It runs over TCP.
  • An open transfer returns every record in one request, replacing all enumeration with an authoritative, complete answer. It is active and needs authorisation to test.
  • It persists because defaults changed while deployments did not, because it produces no symptom, and because permissions get widened under time pressure.
  • Fix: restrict transfers to the known secondaries, authenticated with TSIG.
  • Hardening: separate authoritative from recursive and never expose a resolver (open resolvers become amplifiers); protect the registrar account with multi-factor authentication and registrar lock; monitor expiry and auto-renew; remove records for decommissioned services; consider DNSSEC (integrity of answers, not confidentiality) and encrypted DNS (the channel); log resolver queries and monitor for enumeration; rate limit responses.

Test yourself

  1. What is a zone transfer legitimately for, and what makes an open one dangerous?

It replicates a zone's records from a primary name server to its secondaries so that all authoritative servers hold the same data. An open transfer is dangerous because any party can request it and receive the complete zone, disclosing every host name and record at once, including names no passive source or dictionary would find.

  1. Why does this misconfiguration survive in production for years?

Because it produces no symptom: nothing fails, no user complains and no monitoring fires, so ordinary operations never discover it. It also persists where long-lived servers retain permissive settings from before defaults changed, or where a permission was widened under time pressure and never tightened.

  1. State the fix precisely.

Configure the authoritative servers to permit zone transfers only to the known secondary servers, identified by address, and where supported authenticate those transfers with a shared key (TSIG) so the permission rests on a secret rather than a spoofable address.

  1. Why is the registrar account described as the highest-leverage target in an organisation's DNS?

Because whoever controls it can change the name servers for every domain the organisation owns, redirecting its website, its mail and its services at once. That redirects the organisation's identity rather than compromising a single system, and the account is often protected only by a password, so multi-factor authentication and registrar lock are essential.

munotes.in129

Zone Transfers and DNS Hardening

  1. What does DNSSEC protect, and what does it not?

It protects the integrity and authenticity of DNS answers by signing records so a validating resolver can detect forged or altered responses, which defends against spoofing and cache poisoning. It does not provide confidentiality: queries and answers remain readable, so encrypted DNS over TLS or HTTPS is the separate control for protecting the channel.

Contents This chapter on its own page

munotes.in130

Chapter Twenty-Eight

WHOIS, the Registries and IP Allocation

Syllabus topic Module 1, "DNS Enumeration and Domain Intelligence: ... WHOIS lookup, and ARIN databases to understand infrastructure mapping"

In one line

WHOIS answers "who registered this domain?" and the regional internet registries answer "who holds this block of addresses?". Together they turn a name or an address into an organisation and the range of addresses it controls.

In examination wording: WHOIS is a query protocol and the databases it serves, returning registration information for domain names and for IP address allocations; the five regional internet registries (ARIN, RIPE NCC, APNIC, LACNIC and AFRINIC) allocate address space within their regions and publish which organisation holds each range, enabling an assessor to determine the extent of an organisation's addressable estate.

Two different databases answering two different questions

Students conflate these constantly, so separate them at the start.

Domain WHOIS is about a name. It is served by registrars and registries in the domain-name system, and it answers: who registered company.test, through which registrar, when, until when, and which name servers did they set.

Registry WHOIS is about an address. It is served by the regional internet registries, and it answers: which organisation holds the block containing 203.0.113.45, how large is that block, and who is the technical contact.

Different systems, different operators, different data. The confusion matters because they are used at different points: domain WHOIS at the start, when you have a name; registry WHOIS in the middle, when you have an address and want to know how much else belongs to the same organisation.

Domain WHOIS: what a record holds

A domain WHOIS record has historically shown:

  • the registrant, the person or organisation that owns the domain, with contact details;
  • administrative and technical contacts, often different people;
  • the registrar, the company through which it was registered;
  • the dates: created, last updated, and expiry;
  • the name servers, which ties back to the DNS chapters;
  • the status codes, which record whether the domain is locked against transfer.

What it reveals to reconnaissance. An organisational registrant confirms ownership and often gives a role-based contact. Personal registrant details, where still exposed, give a named individual and their address and telephone number, which is a social-engineering target. The creation date indicates how long the organisation has existed under that name. The name servers confirm the DNS arrangement. And the status codes reveal whether the domain is protected against transfer, which tells an attacker whether a hijack attempt is worth considering.

The expiry date deserves its own paragraph, because it is the most actionable item on the record for a defender. A domain that lapses can be registered by anyone, who then controls the organisation's website addresses and, more damagingly, its mail: they can receive mail sent to the old domain, including password resets. Domains are lost this way regularly, usually secondary ones that nobody is watching because nobody uses them, and the recovery is difficult and sometimes impossible. Enable auto-renewal, keep the registrar account's payment details current, and monitor expiry for every domain the organisation owns, not just the important ones.

munotes.in131

WHOIS, the Registries and IP Allocation

Privacy: why modern WHOIS shows less

A student working from older material will expect names and addresses and mostly will not find them. Two changes account for it.

Registrar privacy services. For a small fee, or free by default with many registrars, the registrant's details are replaced in the public record by the privacy service's own, which forwards correspondence. The real registrant is still known to the registrar, but not to the public.

Data-protection law. The European General Data Protection Regulation caused registries and registrars to redact personal data from public WHOIS output as a matter of course, because publishing an individual's name, address, email and telephone worldwide is difficult to justify. The effect extends well beyond Europe because the operators applied it broadly.

So the modern position is: organisational domains often still show a company name and a role-based contact; domains held by individuals usually show a privacy service or redacted fields. For a defender this means an exposed personal name and address in a WHOIS record is a finding, not the expected state, and the remedy is to enable the registrar's privacy service.

A caution for accuracy: historical WHOIS data persists. Services archive past records, so details redacted today may remain visible in a record from before privacy was applied. Enabling privacy protects the future, not the past.

The regional internet registries

Addresses are allocated in a hierarchy. At the top is the global coordinating body, which allocates large blocks to five regional internet registries, each covering a part of the world. Those allocate to internet providers and to large organisations, who assign to customers.

RegistryRegion
ARINUnited States, Canada, parts of the Caribbean
RIPE NCCEurope, the Middle East, Central Asia
APNICAsia and the Pacific, including India
LACNICLatin America and the Caribbean
AFRINICAfrica

MU's syllabus names ARIN because it is the best known and its database is the model; an Indian organisation's addresses are normally registered with APNIC, and the query is identical in form.

What a registry lookup returns. Given one address, it returns the block that contains it, the organisation that holds the block, the block's size, and technical and abuse contacts. Larger organisations also register autonomous system numbers, which identify their networks in internet routing, and from an autonomous system number all the address ranges it announces can be listed.

munotes.in132

WHOIS, the Registries and IP Allocation

Why the address range is the most useful thing in this chapter

Because it defines boundaries, and boundaries are what both an attacker and an assessor need.

For an attacker, knowing that an organisation holds a range means every address in it is worth examining, including hosts with no DNS name at all. One discovered web server expands into a block of addresses to sweep.

For an assessor, the same lookup answers the question the authorisation chapter raised: what actually belongs to the client? If the address is inside a range registered to the client, it is theirs and the client can authorise testing of it. If it is inside a hosting or cloud provider's range, it is not, and the client cannot grant permission over the provider's infrastructure; the provider's own testing policy applies, and some require notification.

That distinction prevents the commonest scoping error in the profession, and it is why registry lookups belong in the pre-engagement work rather than in the middle of a test.

For a defender, the same lookup is an inventory check: sweeping your own registered ranges finds hosts you have forgotten, which is the point the enumeration chapter made from the other direction.

A worked example

Nisha maps her organisation's estate, beginning with a name and finishing with a boundary.

  1. Domain WHOIS on company.test shows an organisational registrant, a role-based contact, a creation date of 2011, expiry in fourteen months with the status indicating a registrar lock is in place, and two name servers. Sound, except that a second domain the company owns, company-india.test, shows a former employee's personal name and mobile number and expires in six weeks with no lock.
  2. She resolves the main site to an address and queries APNIC, which returns a range held by a hosting provider. So the website is hosted, and the provider's infrastructure is not the client's to authorise.
  3. She resolves the VPN endpoint, queries APNIC again, and this time the range is registered to the company itself, a block of addresses along with an autonomous system number. That range is the client's own estate.
  4. Sweeping the company's own range for names and responses finds three hosts that appear in no DNS record and on no inventory.

Her findings: the second domain's personal registrant data and imminent expiry without a lock (urgent, and a hijack and impersonation risk); the confirmed boundary between client-owned addresses and provider-owned ones, which is recorded in the scope; and three unregistered hosts inside the company's own range.

The middle finding is the one that makes the engagement safe, and it is invisible unless somebody does this lookup.

What beginners get wrong

  • Conflating domain WHOIS with registry WHOIS. One is about a registered name and comes from registrars; the other is about an address block and comes from a regional registry.
  • Expecting personal details. Privacy services and data-protection redaction are now normal. An exposed personal record is a finding, not the default.
  • Assuming privacy fixes the past. Historical WHOIS archives retain what was published before privacy was enabled.
  • Thinking ARIN covers the world. There are five regional registries; India's is APNIC.
  • Ignoring expiry and lock status. A lapsed domain can be taken over and used to receive the organisation's mail, including password resets. Auto-renewal, monitoring and registrar lock are the controls.
  • Assuming everything resolving to a client's name is in scope. If the address belongs to a hosting provider, the client cannot authorise testing of that infrastructure.
munotes.in133

WHOIS, the Registries and IP Allocation

Quick revision

  • Domain WHOIS: registrant, contacts, registrar, created/updated/expiry, name servers, status codes (transfer lock). Served by registrars and registries.
  • Registry WHOIS: which organisation holds an address block, the block's size and abuse contacts, and autonomous system numbers. Served by the five regional registries: ARIN (North America), RIPE NCC (Europe, Middle East), APNIC (Asia-Pacific, India), LACNIC (Latin America), AFRINIC (Africa).
  • Modern domain records are usually privacy-protected or redacted; an exposed personal registrant is a finding. Historical archives persist.
  • Expiry and registrar lock are the actionable defensive items: a lapsed domain can be hijacked and used to receive the organisation's mail.
  • The address range is the most useful output: it expands one host into an estate for enumeration, and it settles what the client owns and can lawfully authorise.

Test yourself

  1. Distinguish domain WHOIS from a regional registry lookup.

Domain WHOIS returns registration details for a name (registrant, registrar, dates, name servers, status) and is served by registrars and domain registries. A regional registry lookup returns which organisation holds the address block containing a given IP address, the block's extent and its contacts, and is served by one of the five regional internet registries.

  1. Why has WHOIS output become less revealing, and what does that mean for an assessor?

Registrar privacy services replace registrant details with a proxy, and data-protection law, principally the GDPR, caused widespread redaction of personal data. For an assessor it means exposed personal details in a record are a finding to report rather than the expected result, and that historical archives may still show pre-redaction data.

  1. Which registry serves India, and why does the syllabus mention ARIN?

APNIC serves the Asia-Pacific region including India. The syllabus names ARIN because it is the best-known regional registry and its database is the model for the others; the query technique is identical.

  1. Why is an address-range lookup important before testing begins?

Because it determines what the client actually owns. Addresses inside a range registered to the client are the client's own estate and can be authorised; addresses inside a hosting or cloud provider's range belong to that provider, which the client cannot authorise, so the provider's testing policy applies instead.

munotes.in134

WHOIS, the Registries and IP Allocation

  1. What are the risks of an unmonitored domain expiry, and what controls address them?

An expired domain can be registered by anyone, who can then serve content from the organisation's addresses and receive mail sent to the domain, including password-reset messages, enabling impersonation and account takeover. The controls are auto-renewal, current payment details on the registrar account, expiry monitoring for every domain owned, and registrar lock against unauthorised transfer.

Contents This chapter on its own page

munotes.in135

Chapter Twenty-Nine

The Psychology: the Levers an Attacker Pulls

Syllabus topic Module 1, "Social Engineering and Human Exploitation Techniques: Examine psychological manipulation attacks"

In one line

Social engineering works by triggering ordinary, useful human instincts at the wrong moment. The attacker does not defeat your judgement; they arrange a situation in which your normal judgement produces the answer they want.

In examination wording: social engineering exploits predictable features of human decision-making, principally deference to authority, response to urgency and fear, reciprocity, social proof, liking and familiarity, commitment and consistency, and the tendency to comply with requests that resemble routine business, in order to induce a target to disclose information or perform an action contrary to security.

Why start with the psychology

Two reasons.

It makes the techniques learnable rather than listable. Phishing, pretexting, baiting and tailgating look like four unrelated things until you notice that each is a delivery mechanism for the same small set of levers. Learn the levers and the techniques become variations; learn only the techniques and you are memorising.

It is the defence. The next chapters will show that technical controls help but cannot be sufficient, because the target is a person with legitimate access doing something they are permitted to do. What actually protects people is recognition: the moment someone notices "this message is making me feel I must act immediately and cannot check", the spell breaks. You cannot teach recognition by listing scams, because the next scam will look different. You teach it by naming what the scam is doing.

A framing that matters, and that examiners increasingly expect: the human is not the weakest link, and saying so is a design failure dressed as an excuse. The responses below are what make organisations work. A person who never deferred to authority, never helped a colleague under time pressure, and never trusted a familiar face would be unemployable. The attack abuses cooperation, and a system that requires people to be permanently suspicious to stay safe is a badly designed system.

The levers

Authority

People comply with requests that appear to come from someone entitled to make them. It is efficient: an organisation in which every instruction was independently verified would grind to a halt.

How it is abused. A message from "the IT department", "the CEO", "the bank", "the tax office", or "your manager". The attacker does not need real authority, only its markers: the right logo, the right tone, a title in a signature, a plausible sender address.

Why it works even on the sceptical. Authority combines with hierarchy. Questioning a request that appears to come from a senior person carries a social cost, and the target weighs a small risk of being fooled against a definite risk of appearing obstructive. Junior and new staff feel this most sharply, which is why both are targeted.

munotes.in136

The Psychology: the Levers an Attacker Pulls

What defeats it. Verification through a separate, known channel, and a culture in which verifying a senior person's request is explicitly expected rather than tolerated. The rule has to be stated by senior people themselves, or the social cost remains.

Urgency and fear

A deadline or a threat compresses the time available to think. "Your account will be suspended in two hours." "The payment must go today or we lose the contract." "There has been suspicious activity on your account."

Why it works. Careful evaluation takes time and attention. Remove the time and the target falls back on fast pattern-matching, which is exactly the mode in which a plausible-looking message passes. Fear narrows attention further, onto the threat and away from the message's oddities.

The tell. Urgency that is manufactured rather than inherent is the single most reliable indicator of a social-engineering attempt. Genuine business urgency exists, but it rarely also insists that you must not check with anyone.

What defeats it. A rule that certain categories of request are never urgent: changes to payment details, password resets for another person, transfers above a threshold. If the process says these always take a verification step, then urgency cannot bypass it, because the urgency is not what the procedure responds to.

Reciprocity

People feel obliged to return a favour. Give something small first and the target is more willing to give something back.

How it is abused. The attacker provides "help" before asking: a caller from "IT support" who fixes a minor problem and then asks the user to confirm their password; a free tool, a useful document, a held door.

What defeats it. Recognising that a favour does not create an obligation to bypass a control, and process rules that do not bend for goodwill.

Social proof

People look to others' behaviour to decide what is normal. "Everyone in your department has already completed this." "Three of your colleagues have signed in to the new portal."

How it is abused. A claim that others have complied lowers resistance and makes hesitation feel like being the odd one out. It is especially effective on new joiners, who have no baseline for what is normal here.

What defeats it. Making the true norm visible: if staff know the organisation never asks for credentials by email, a claim that everyone else has provided theirs contradicts a known rule rather than an unknown one.

Liking and familiarity

People comply more readily with those they like or recognise. Attackers build rapport, mirror language, mention shared connections, or simply appear familiar.

How it is abused. A friendly caller who mentions a colleague's name; a message from a compromised genuine contact, which is the strongest form, because the familiarity is real. This is why a compromised account inside a supply chain is so dangerous: the trust is not simulated.

munotes.in137

The Psychology: the Levers an Attacker Pulls

What defeats it. Verification that does not depend on recognition. A known contact's account can be compromised, so a request for something sensitive is verified by channel, not by whether the sender seems familiar.

Commitment and consistency

Once someone has agreed to something small, they are more likely to agree to something larger consistent with it. An attacker may open with a trivial, harmless request and escalate.

What defeats it. Recognising the escalation pattern, and process gates that apply regardless of what was agreed earlier in the conversation.

The routine

The quietest lever, and the one that most often carries a real attack. A request that looks like ordinary business is not scrutinised, because scrutiny is reserved for the unusual. An invoice, a delivery note, a shared document, a calendar invitation, a request to update bank details from a supplier you actually use.

Why it works. The other levers push; this one simply does not trigger the check. Most successful business-email-compromise attacks rely on it, not on drama.

What defeats it. Process rather than alertness. If updating a supplier's bank details always requires a callback to a number already on file, the attack fails whether or not anyone felt suspicious.

Why these are hard to resist even when you know them

Three honest observations, and a good answer includes them.

Knowing about a bias does not switch it off. Awareness reduces susceptibility; it does not eliminate it. Security professionals are phished successfully.

The attacker only needs one success. A message sent to two hundred staff needs one person having a bad morning.

The target is doing their job. The finance clerk who pays an invoice is performing their function. The attack is shaped to look like the work.

Those three together are the argument for the defensive structure of the whole block: awareness lowers the rate, and controls must make a single human error survivable. That is the multi-factor authentication and verification-procedure argument, and it is why the defence chapter later refuses to rest on training alone.

A worked example: reading the levers in one message

An email arrives at a finance clerk's address. It appears to come from the Managing Director, whose name and title are on the company website. It reads: the MD is in a meeting and cannot take calls; a supplier payment must be released today or a contract is lost; the bank details have changed and are given below; please confirm when done.

Name the levers:

Element of the messageLever
Appears to come from the Managing DirectorAuthority
"Must be released today or the contract is lost"Urgency and fear
"In a meeting and cannot take calls"Pre-empts verification
A supplier payment, an ordinary taskThe routine
"Please confirm when done"Commitment: invites a small compliance
munotes.in138

The Psychology: the Levers an Attacker Pulls

Four levers and a pre-emptive block on the one defence that would work, assembled from information that was all public: the MD's name from the website, the clerk's address from the email format, the supplier's name perhaps from a press release. Nothing here required any technical compromise.

Now the defence. Not "the clerk should have been suspicious", which is hindsight. The organisation should have had a rule that a change of bank details is always verified by a call to a number already on file, regardless of who asks or how urgent it is. Under that rule the clerk does not need to detect anything; the process catches it, and the "cannot take calls" line becomes the reason to stop rather than to proceed.

What beginners get wrong

  • Calling people the weakest link. These responses make organisations function; the attack abuses cooperation. A design that needs constant suspicion is the failure.
  • Thinking awareness alone is enough. It lowers the rate and never to zero, and the attacker needs one success. Controls must make one error survivable.
  • Looking for spelling mistakes. Poor writing was never a reliable signal and is not now. The signals are structural: manufactured urgency, a request to bypass a process, pressure not to verify.
  • Assuming a familiar sender is safe. A genuine contact's account can be compromised, and that is the most effective form of the attack.
  • Blaming the person who clicked. It is unfair and operationally harmful: blame makes people hide mistakes, which lengthens the time to respond.
  • Treating the quiet attacks as less serious. The routine-looking request, not the dramatic one, carries most successful business-email compromise.

Quick revision

  • Social engineering triggers normal, useful instincts at the wrong moment; it does not defeat judgement, it arranges the situation.
  • Levers: authority (markers of entitlement, plus the social cost of questioning), urgency and fear (compress thinking time; manufactured urgency is the strongest tell), reciprocity (a favour first), social proof ("everyone else has"), liking and familiarity (strongest when a genuine account is compromised), commitment and consistency (small agreement then escalation), and the routine (looks like ordinary business, so nothing triggers a check).
  • Defences map to levers: verification through a separate known channel; rules that certain requests are never urgent; process gates that do not bend for goodwill, familiarity or prior agreement; making the true norm visible.
  • Knowing the biases does not remove them, the attacker needs one success, and the target is doing their job, so controls must make a single error survivable.
munotes.in139

The Psychology: the Levers an Attacker Pulls

Test yourself

  1. Why is it said that social engineering does not defeat a person's judgement?

Because it arranges a situation in which normal, useful judgement produces the attacker's desired answer: deference to apparent authority, action under apparent urgency, and non-scrutiny of what looks like routine business are all sensible responses being triggered at the wrong moment.

  1. Name five levers and give one sentence on how each is abused.

Authority, by imitating someone entitled to make the request; urgency and fear, by compressing the time available to think; reciprocity, by providing a small favour before asking; social proof, by claiming colleagues have already complied; and familiarity, by building rapport or by using a genuinely compromised known account.

  1. Which single element of a message is the most reliable indicator of a social-engineering attempt, and why?

Manufactured urgency, particularly when combined with a reason the request cannot be verified. Genuine business urgency exists, but it rarely also insists that the recipient must not check with anyone, so pressure plus a pre-emptive block on verification is the structural signal.

  1. Why is "the routine" lever more dangerous than the dramatic ones despite being the quietest?

Because the other levers push the target into acting while this one simply fails to trigger any check: an ordinary-looking invoice or supplier update is processed as work, and scrutiny is reserved for the unusual. Most successful business-email compromise relies on it.

  1. Why must defences not rest on awareness training alone?

Because knowing about a bias does not switch it off, the attacker needs only one person to comply once, and the target is performing their normal duties when deceived. Controls such as multi-factor authentication and mandatory verification of sensitive changes are required so that a single human error does not by itself cause harm.

Contents This chapter on its own page

munotes.in140

Chapter Thirty

Phishing, Spear Phishing, Whaling, Smishing and Vishing

Syllabus topic Module 1, "Social Engineering and Human Exploitation Techniques: Examine psychological manipulation attacks including phishing"

In one line

Phishing is a fraudulent message designed to look trustworthy so the reader clicks, opens, replies or enters credentials. The variants differ in who is targeted (anyone, a named person, an executive) and which channel is used (email, text message, voice call).

In examination wording: phishing is the sending of fraudulent communications that appear to originate from a reputable source in order to induce recipients to reveal sensitive information, install malicious software, or perform actions such as transferring funds; spear phishing targets specific individuals using researched detail, whaling targets senior executives, smishing uses SMS and vishing uses voice telephony.

The family, on two axes

Everything in this chapter is one attack varying in two directions.

Untargeted (mass)Targeted (researched)
EmailPhishingSpear phishing; whaling when the target is an executive
SMSSmishingTargeted smishing
VoiceVishing (robocalls)Targeted vishing
Instant messaging, social mediaSpam-style luresTargeted approaches

The targeting axis governs how convincing the message can be and how many are sent. The channel axis governs which technical defences apply, because email has authentication mechanisms that SMS and voice do not.

Mass phishing

The attacker sends a generic message to very many addresses, imitating a bank, a delivery company, a tax authority or a large service provider, and relies on volume: a small fraction of recipients will hold an account with that organisation and a smaller fraction will act.

What makes it work. Scale, plus the fact that the imitated brands are ones nearly everyone uses. It costs almost nothing per message.

What limits it. It is generic, so it contains nothing specific to the recipient, and mail filtering catches a large share because the same message is sent to millions and is quickly recognised.

The common goals. A credential-harvesting page imitating a login; an attachment carrying malware; a link to an exploit; or a reply that begins a conversation.

Spear phishing

The targeted form, and by far the more dangerous. The attacker researches a specific person, using exactly the reconnaissance from the earlier block, and writes a message for them alone.

What the reconnaissance supplies, tying this block to the last one:

  • the email format, so the message reaches the right person (from the OSINT-on-people chapter);
  • the target's name, role and manager, so the message can claim plausible authority;
  • context: a project, a supplier, a recent announcement, a conference the person attended;
  • the mail provider, from the MX record, so an imitated login page can match what the target sees daily;
  • whether the domain's DMARC policy permits forgery, from the TXT record.

The result is a message that names a real project, appears to come from a real colleague, and asks for something that person plausibly would ask for. Mail filters have little to work with, because the message is unique, contains no malicious attachment if the goal is a reply, and may come from a genuine but compromised account.

munotes.in141

Phishing, Spear Phishing, Whaling, Smishing and Vishing

Whaling is spear phishing aimed at senior executives. They are attractive because they can authorise payments, because their instruction carries weight with others, and because their assistants act on their behalf. A common pattern is not to attack the executive at all but to impersonate them to finance staff, which is the business-email-compromise shape from the psychology chapter.

Business email compromise deserves naming as the financially most damaging form. There is often no malicious link or attachment at all: the message is plain text asking for a payment or a change of bank details. Nothing for a filter to detect, and the defence is entirely procedural.

Smishing and vishing

Smishing, over SMS, exploits three differences from email. Links are shortened, so the destination is hidden. Phone interfaces show less context and make inspection harder. And SMS carries an implicit trust, since people receive genuine bank alerts and delivery notices that way. Sender identifiers can be spoofed in many networks, so the message may appear in the same conversation thread as genuine messages from the real organisation, which is powerfully convincing.

Vishing, over voice, adds the pressure of a live conversation: the target cannot pause to think, and refusing a person feels harder than ignoring a message. Caller identification can be forged. A frequent pattern is the "support" call claiming a problem with the target's computer or account, and a more sophisticated one is a call that follows a phishing email to lend it credibility.

A combination worth knowing: an attacker who has a password may phish or vish the one-time code that protects the account, calling as "the bank's fraud team" and asking the victim to read out the code they have just received. This is why codes always carry a warning that nobody legitimate will ask for them, and why phishing-resistant factors matter, a point the defence chapter takes up.

How the deception is constructed

A student should be able to describe the construction, because recognising it is the defence.

The sender. Either a forged address in the target's own domain (which works when DMARC is absent or permissive), a look-alike domain differing by a character or a plausible suffix, a display name set to a trusted person while the real address is unrelated (very effective on phones, which often show only the display name), or a genuine compromised account, which defeats every sender check.

The link. Display text that differs from the destination; a look-alike domain; a shortener; a legitimate service abused to host the page; or a redirect through a trusted site.

munotes.in142

Phishing, Spear Phishing, Whaling, Smishing and Vishing

The landing page. A copy of a real login page, often fetched live from the original so it is pixel-accurate, sometimes forwarding entered credentials to the real site so the victim ends up logged in and notices nothing.

The pretext. One or more of the levers from the previous chapter, most often authority plus urgency, with a reason the request cannot be verified.

Recognition, and the signals that are not reliable

Signals that do help:

  • The request is for credentials, a code, a payment, or a change of payment details. Legitimate organisations do not ask for passwords or one-time codes.
  • Manufactured urgency, especially with a reason not to verify.
  • A mismatch between the display name and the actual address, or between link text and destination.
  • The message asks you to break a normal process.
  • It arrives out of the expected channel for that kind of request.

Signals that are not reliable, and this is where teaching often goes wrong:

  • Spelling and grammar. Targeted messages are well written, and automated translation has removed this signal.
  • A logo that looks right. Trivially copied.
  • A link that begins with HTTPS. Certificates are free; encryption says nothing about honesty.
  • A familiar sender. The account may be compromised.
  • "I was expecting something like this." Attackers time messages to expectations, around results, payroll, renewals and deliveries.

The structural conclusion, which is the examinable one: recognition should rest on what the message asks you to do, not on how it looks.

Defences, in layers

Fully treated in the two chapters that follow, summarised here so the family is complete.

Technical. Email authentication (SPF, DKIM, DMARC) to make domain forgery harder to deliver; mail filtering and link inspection; blocking or flagging look-alike domains; and multi-factor authentication, which turns a harvested password into a failed login. Phishing-resistant factors bound to the site defeat even real-time credential relaying.

Procedural. Verification through a known second channel for any payment or bank-detail change; a rule that such requests are never urgent; and clear statements of what the organisation will never ask for.

Human. Training that teaches the levers rather than the spelling mistakes; simulated exercises used to measure and educate, never to punish; and above all an easy, no-blame reporting route, because the speed of the response depends on someone saying "I think I clicked something" within minutes rather than hiding it for a day.

A worked example

A university finance officer receives an email. The display name is the Registrar's; the actual address is at a domain one character different from the university's. It refers to a building project by its real name, states that a contractor's account details have changed, gives new details, says payment must go today because works are stopping, and adds that the Registrar is travelling and unreachable.

munotes.in143

Phishing, Spear Phishing, Whaling, Smishing and Vishing

Reading it with the chapter's tools:

  • Class: spear phishing shading into business email compromise. No link, no attachment, so filtering has little to act on.
  • Reconnaissance used: the Registrar's name and title (public), the project name (a press release), the finance officer's address (the email format), and perhaps the contractor's name (a tender notice).
  • Construction: a look-alike domain with a trusted display name, which on a phone shows only "Registrar".
  • Levers: authority, urgency, the routine (paying a contractor is the job), and a pre-emptive block on verification.
  • Unreliable signals: the message is well written, plausible and correct in every detail, so "look for mistakes" fails entirely.
  • What stops it: the procedural control. A rule that bank-detail changes are verified by calling a number already held on file means the officer does not need to detect anything, and "unreachable" becomes the reason to stop rather than to proceed.
  • What limits it if it succeeds: rapid, blameless reporting, because a payment recalled within the hour is often recoverable and one reported next week is not.

What beginners get wrong

  • Teaching spelling mistakes as the signal. Targeted messages are well written; this advice fails exactly where it is most needed.
  • Thinking phishing always involves a link or attachment. Business email compromise is often plain text, which is why it evades filtering and why the defence is procedural.
  • Treating a familiar sender as safe. Compromised genuine accounts are the most effective vector.
  • Believing a padlock or HTTPS indicates legitimacy. Certificates are free and say nothing about who the site belongs to.
  • Forgetting SMS and voice. They lack email's authentication mechanisms, can be spoofed into genuine message threads, and voice adds live pressure.
  • Using phishing simulations punitively. It suppresses reporting, and reporting speed is what limits damage.

Quick revision

  • One attack, two axes: targeting (mass phishing, spear phishing, whaling) and channel (email, smishing by SMS, vishing by voice).
  • Spear phishing is built from reconnaissance: email format, names and roles, context, the mail provider to imitate, and the DMARC policy.
  • Business email compromise often has no link or attachment, so filters cannot see it; the defence is procedural.
  • Construction: forged or look-alike sender, misleading display name, deceptive link, cloned landing page, and a pretext using authority plus urgency.
  • Reliable signals: it asks for credentials, a code, a payment or a change of bank details; manufactured urgency with a reason not to verify; display-name or link mismatch; a request to break process. Unreliable: spelling, logos, HTTPS, familiarity.
  • Layers: email authentication and filtering plus multi-factor authentication; verification through a second known channel; training on levers, and a no-blame reporting route.
munotes.in144

Phishing, Spear Phishing, Whaling, Smishing and Vishing

Test yourself

  1. Distinguish phishing, spear phishing and whaling, and say which is hardest for a mail filter to catch.

Phishing is generic and sent in volume; spear phishing targets a named individual using researched detail; whaling targets senior executives. Spear phishing, particularly in its business-email-compromise form, is hardest to filter because each message is unique, often contains no link or attachment, and may come from a genuinely compromised account.

  1. What does reconnaissance contribute to a spear-phishing message?

The email format so the message is addressed correctly, the target's name, role and reporting line so it can claim plausible authority, contextual detail such as projects and suppliers to make it convincing, the mail provider to imitate on any login page, and the domain's DMARC policy, which indicates whether a forged sender will be delivered.

  1. Why is "look for spelling mistakes" poor advice?

Because targeted messages are carefully written and automated translation has removed the signal, so the advice fails precisely against the attacks that matter most. Recognition should rest on what the message asks the recipient to do, not on how it reads.

  1. How do smishing and vishing differ from email phishing in the defences available?

Email has authentication mechanisms (SPF, DKIM, DMARC) and mature filtering, whereas SMS and voice largely lack equivalents: sender identifiers and caller identification can be forged, spoofed messages can appear inside genuine threads, links are shortened and phone interfaces hide context, and a live call adds time pressure that a message does not.

  1. Why is a no-blame reporting route treated as a security control?

Because the damage from a successful phish depends heavily on response time: a fraudulent payment recalled within the hour is often recoverable and credentials revoked quickly limit access. Blame makes people conceal mistakes, which delays response, so a culture in which reporting is easy and unpunished materially reduces loss.

Contents This chapter on its own page

munotes.in145

Chapter Thirty-One

Pretexting, Baiting, Impersonation and Tailgating

Syllabus topic Module 1, "Social Engineering and Human Exploitation Techniques: Examine psychological manipulation attacks including phishing, pretexting, baiting, and impersonation"

In one line

Beyond the fraudulent message lie four techniques that work by inventing a reason (pretexting), offering something tempting (baiting), becoming someone trusted (impersonation), or simply walking in behind somebody (tailgating).

In examination wording: pretexting is the construction of a fabricated scenario to establish legitimacy for a request; baiting offers something desirable to induce the target to take an unsafe action; impersonation is the assumption of a trusted identity in person, by telephone or online; and tailgating, also called piggybacking, is following an authorised person through a physical access control.

Pretexting

What it is. The attacker invents a scenario, a pretext, that makes the request reasonable. The deception is not primarily in the request but in the context surrounding it.

The pretext supplies three things: a reason the attacker is asking, a role that entitles them to ask, and an expectation of how the target should respond. Done well, the target is not deciding whether to trust a stranger; they are performing a routine task within a story they have already accepted.

Recurring pretexts, which a student should recognise:

  • New IT contractor setting up systems, who needs the user to confirm details or approve a prompt.
  • Auditor or compliance officer requiring information for a review, exploiting the reluctance to obstruct an audit.
  • Supplier's accounts department confirming details for an invoice, the entry point for payment fraud.
  • New employee who has not yet been given access and needs help, exploiting willingness to assist a colleague.
  • Survey or research collecting apparently innocuous organisational detail that is really reconnaissance.
  • Emergency: a senior person locked out before an important meeting, combining pretext with urgency and authority.

Why it is effective. It is built from the routine lever: the request itself is ordinary, so nothing triggers scrutiny. A good pretext also pre-empts verification by explaining why the normal check is impossible (the manager is travelling, the system is down, this is urgent because of an audit deadline).

Defences. Verification through an independently obtained channel, which is the defining word: not the number in the email signature, but the number already held on file. Procedures that do not vary for the story. And a specific, teachable rule for help desks, the most pretexted function in any organisation: identity is verified by a defined procedure before any account action, every time, regardless of how plausible or urgent the caller sounds. Help-desk password resets and multi-factor re-enrolments are a primary route into organisations precisely because the function exists to help people who cannot get in.

Baiting

What it is. The attacker offers something the target wants and relies on curiosity or greed to make them take an unsafe action. Where phishing pushes, baiting waits.

Physical baiting. The classic is removable media left where employees will find it, in a car park, a lobby, a canteen, sometimes labelled to invite curiosity ("Salaries", "Redundancies", "Confidential"). A device that a person plugs in can deliver malware, and some hardware presents itself to the computer as a keyboard and types commands, which defeats defences that only block file execution. Studies of this behaviour have repeatedly found that a substantial proportion of found media is connected, often by people trying to identify the owner and return it, which is a helpful instinct being exploited.

munotes.in146

Pretexting, Baiting, Impersonation and Tailgating

Digital baiting. Free software, cracked applications, a desirable document, an offer, a fake update prompt.

Defences. Disable or restrict removable media by policy and technically; use endpoint controls that limit what a newly attached device may do, including restricting automatic recognition of new input devices; provide a safe route to hand in found items so the helpful instinct has somewhere to go; and train on the specific scenario, because it is concrete and memorable in a way that abstract advice is not.

Impersonation

What it is. The attacker assumes a trusted identity. It underlies much of the rest of this block: a phishing email impersonates a sender, a vishing call impersonates support, a pretext usually requires an identity to inhabit.

In person, impersonation relies on props and expectations more than on documents: a high-visibility jacket and a clipboard, a delivery uniform, a contractor's toolbag, a visitor badge from a previous visit, or simply confidence. People read roles rather than credentials; someone dressed as a cleaner at the expected hour is not examined.

Common physical impersonations: delivery driver, maintenance or utility engineer, fire-safety inspector, IT contractor, new starter, and auditor.

The legal position is sharp. Impersonation to deceive by means of a computer resource is exactly what section 66D punishes, and physical impersonation to obtain entry is trespass and may be other offences. An unauthorised "test" of a building or a help desk is not a grey area. Social engineering is tested only where the engagement's scope expressly authorises it, and a tester doing it carries their authorisation letter so that the exercise ends with a document rather than an arrest.

Defences. Verify identity by a defined process rather than by appearance; require and check visitor registration and escorting; issue visually distinct badges for staff, contractors and visitors; confirm expected visits with the requesting department before granting access; and make it culturally normal to ask an unescorted stranger who they are looking for, which requires management to say explicitly that challenging is expected and that nobody will be criticised for it.

Tailgating

What it is. Following an authorised person through a controlled door, so the attacker never presents a credential at all. Piggybacking is sometimes distinguished as the case where the authorised person knowingly holds the door; tailgating where they do not notice.

munotes.in147

Pretexting, Baiting, Impersonation and Tailgating

Why it works so reliably, and it does: it exploits politeness, not inattention. Holding a door for the person behind you is good manners, and refusing feels rude. The attacker helps by giving a reason not to challenge: carrying a large box, being on the phone, balancing coffee cups, wearing a uniform, or arriving in a crowd at the start of the day.

Defences. Physical measures work better than exhortation: airlocks or turnstiles that admit one person per authentication; anti-passback rules so a credential cannot be used to enter twice without an exit between; and door sensors that alarm when a door is held open. Beyond hardware, reception staff trained and explicitly empowered to challenge, escort policies for all visitors, and the cultural change of making it normal to ask. The honest point is that training alone struggles against politeness, which is why organisations that care about this buy turnstiles.

Once inside, the value is large: network sockets, unlocked screens, documents on desks and in printers, and the trust extended to anyone who is evidently already inside. This is the argument for clear-desk and screen-lock policies and for not treating physical presence as authentication on the network.

Combining the techniques

Real attacks chain them, and an examination question often describes a chain.

A representative sequence: reconnaissance gives the names of the IT manager and a supplier; a vishing call to the help desk, using a pretext (a new starter) and impersonating that supplier's engineer, obtains the name of the remote-access system; a spear-phishing email to a named employee, referencing the supplier by name, harvests credentials; and if remote access fails, tailgating into the building at the morning rush provides a network socket.

Each step is modest and each makes the next more credible, which is the pattern to recognise. It is also why isolated defences fail: a control that stops one step in a chain is worth more than it appears, because the chain cannot continue.

A worked example

A tester engaged with explicit authorisation for physical and social-engineering testing, carrying a signed letter, attempts entry to an office.

  • Reconnaissance: a photograph on the company's social media shows the badge design and the reception layout; a job advertisement names the cleaning contractor.
  • Pretext and impersonation: the tester arrives at 08:45 in the cleaning contractor's branded shirt, carrying supplies.
  • Tailgating: staff are arriving in numbers; a person ahead holds the door, seeing full hands and a uniform. No credential is presented.
  • Inside: two unlocked screens, printed documents in the printer tray, and an unused meeting-room network socket.
  • The test ends when a staff member challenges the tester at 09:20 and the tester produces the authorisation letter. That challenge is recorded as a positive finding, and the person who made it should be commended in the report.
munotes.in148

Pretexting, Baiting, Impersonation and Tailgating

Findings and recommendations: install a turnstile or airlock at the main entrance (the only control that reliably addresses tailgating); enforce clear-desk and automatic screen locking; disable unused network sockets and require authentication for network access; verify contractor visits with the facilities team in advance; and, since one employee did challenge, recognise it publicly to reinforce the behaviour.

That last recommendation is deliberate. A social-engineering report that lists only failures teaches staff that the exercise exists to catch them out, which suppresses the reporting and challenging the organisation needs.

What beginners get wrong

  • Thinking pretexting is about lying convincingly. It is about constructing a context in which the request is routine, and pre-empting verification.
  • Believing people fall for baiting through foolishness. Much found media is connected by people trying to identify the owner. The instinct is helpful and is being exploited; give it a safe outlet.
  • Treating tailgating as inattention. It is politeness. Exhortation works poorly against it; turnstiles and anti-passback work well.
  • Assuming a badge or uniform is verification. People read roles, not credentials. Verification must be a process.
  • Testing social engineering without explicit authorisation. Impersonation by computer engages section 66D and physical entry is trespass; it is authorised expressly or not at all.
  • Writing a report that names and blames individuals. It suppresses challenging and reporting, which are the behaviours the organisation most needs.

Quick revision

  • Pretexting: a fabricated scenario supplying a reason, a role and an expectation; works through the routine lever and usually pre-empts verification. Help desks are the most pretexted function; identity verification must be procedural and invariant.
  • Baiting: offers something desirable, physically (found removable media, sometimes presenting as a keyboard) or digitally. Restrict media, control new devices, provide a safe hand-in route.
  • Impersonation: assuming a trusted identity, relying on role-reading rather than credentials. Engages s.66D by computer and trespass physically; requires explicit scope authorisation.
  • Tailgating (and piggybacking): entering behind an authorised person, exploiting politeness. Addressed by turnstiles, airlocks, anti-passback and door alarms more than by training.
  • Real attacks chain these; breaking any one link stops the chain.
  • Report findings about process, and record and commend successful challenges.

Test yourself

  1. What does a pretext supply, and why is pre-empting verification part of it?

It supplies a reason the attacker is asking, a role entitling them to ask, and an expectation of how the target should respond, so the request seems routine. Pre-empting verification (the manager is travelling, the system is down) removes the one defence that would defeat it, so a good pretext includes it by design.

munotes.in149

Pretexting, Baiting, Impersonation and Tailgating

  1. Why is baiting with found removable media effective, and what defences address it?

Because curiosity and, more often, the helpful instinct to identify and return the owner lead people to connect it; some devices present as keyboards and type commands, defeating file-based controls. Defences are restricting removable media technically and by policy, endpoint control over newly attached devices, a safe route for handing in found items, and specific training on the scenario.

  1. Why does tailgating succeed even in organisations with badge access, and what actually stops it?

Because it exploits politeness rather than inattention: holding a door is good manners and challenging feels rude, and attackers supply reasons not to challenge such as full hands or a uniform. Physical controls stop it: turnstiles or airlocks admitting one person per authentication, anti-passback, and alarms on doors held open, supported by empowered reception staff and escort policies.

  1. What is the legal position of impersonation in a security test?

Impersonation to deceive by means of a computer resource falls under section 66D of the IT Act, and physical impersonation to gain entry is trespass. It is therefore lawful only where the engagement's scope expressly authorises social-engineering and physical testing, and the tester carries the authorisation letter.

  1. Why should a social-engineering report avoid naming individuals who were deceived, and what should it record instead?

Because naming individuals assigns blame for behaviour the organisation relies on and suppresses the challenging and reporting that limit damage. The report should record process failures and recommend controls, and should positively record instances where staff did challenge or report, so the desired behaviour is reinforced.

Contents This chapter on its own page

munotes.in150

Chapter Thirty-Two

A Worked Case: Analysing a Real Attack

Syllabus topic Module 1, "Social Engineering and Human Exploitation Techniques: ... Analyze real-world social engineering cases"

In one line

Analysing a social-engineering attack means answering four questions in order: which lever was pulled, what reconnaissance made it work, which control failed, and what single control would have stopped it.

In examination wording: the analysis of a social-engineering incident identifies the psychological techniques employed, the information gathered beforehand that lent the approach credibility, the point at which organisational controls failed to prevent or detect the attack, and the specific mitigations that would have interrupted the attack chain.

Why a method rather than a list of famous cases

Students who revise by memorising incidents can describe them and cannot analyse a new one, which is what the examination and the job both require. A method transfers.

The method also enforces a discipline that matters professionally: it moves the answer away from "the employee should have been more careful", which is hindsight and produces no improvement, toward "this process had no verification step", which produces a fix. An analysis that ends in blame has not finished.

The four questions

1. Which lever was pulled? Identify the psychological techniques from the levers chapter: authority, urgency and fear, reciprocity, social proof, liking and familiarity, commitment, and the routine. Most real attacks use two or three in combination, and naming them shows why the target behaved reasonably.

2. What reconnaissance made it plausible? Identify what the attacker had to know beforehand and where they got it. This is the step that connects the block to the footprinting chapters, and it is where the defensive opportunity often lies, because some of that information need not have been public.

3. Which control failed, or was absent? Be precise. Not "security was weak" but "there was no requirement to verify a change of bank details through an independent channel", or "the help desk reset a password without verifying identity", or "the account had no second factor".

4. What single control would most likely have stopped it? Force yourself to name one, because it makes you rank rather than list, and because a report that recommends twenty things equally gets none of them done. Usually the answer is a process gate or multi-factor authentication.

A good analysis then adds a fifth, optional but valuable: what would have limited the damage once it succeeded, since prevention eventually fails.

Case one: the supplier payment

The narrative. A manufacturing company's accounts payable clerk receives an email that appears to come from a regular supplier's accounts department. It refers to a specific outstanding invoice by number, states that the supplier has changed banks, gives new account details, and asks that the pending payment be redirected. The tone is ordinary and unhurried. The clerk updates the supplier record and pays. Three weeks later the real supplier asks why the invoice is unpaid.

munotes.in151

A Worked Case: Analysing a Real Attack

Question 1: which levers?

  • The routine, and this is the principal one. Paying a supplier's invoice is the clerk's job, and a notification of changed bank details is a thing suppliers genuinely send. Nothing about the request was unusual, so nothing triggered scrutiny.
  • Authority, mildly: the supplier's accounts department is entitled to state its own bank details.
  • Familiarity: a real supplier, a real invoice number, an established relationship.
  • Notably not urgency. The absence is instructive: the attacker did not need pressure because the request was already normal, and urgency might have prompted a check.

Question 2: what reconnaissance? The attacker knew the supplier relationship existed, the invoice number, and the clerk's address. The most likely source is a compromised mailbox at either company, giving access to genuine correspondence, which also explains the accurate invoice number and matching tone. Alternatively, public tender or contract records plus the email format.

Question 3: which control failed? Precisely: there was no requirement to verify a change of banking details through an independently obtained channel. The company treated an emailed instruction as sufficient authority to change where money is sent. Secondarily, there was no out-of-band confirmation to the supplier that details had changed, and no alerting on a payment to newly changed details.

Question 4: the single control. A mandatory callback to a telephone number already held on file (not one supplied in the message) before any change to payment details takes effect. This defeats the attack completely and regardless of how convincing the email was, because the attacker does not control the number on file.

Question 5: what would have limited the damage? Detecting it sooner. An alert when a payment is made to bank details changed within the last thirty days would have surfaced it in days rather than three weeks, and funds recalled quickly are sometimes recoverable.

The lesson. The most costly social engineering is often the least dramatic. There was no malware, no link, no urgency and nothing for a filter to detect. A control that depends on someone feeling suspicious would not have worked, because there was nothing to feel suspicious about.

Case two: the help desk and the second factor

The narrative. An attacker has obtained an employee's password from an unrelated breach where the employee reused it. The corporate account requires a second factor, a code from an application on the employee's phone, so the password alone fails.

The attacker telephones the company's IT help desk, gives the employee's name and employee number, and says they have a new phone and cannot generate codes, and that they have a customer presentation in twenty minutes. The help desk agent, following a procedure that asks for name, employee number and date of birth, all of which the attacker has from public and breach sources, resets the second-factor enrolment. The attacker registers their own device and signs in.

munotes.in152

A Worked Case: Analysing a Real Attack

Question 1: which levers?

  • Urgency: the presentation in twenty minutes, compressing the agent's decision and making a thorough check feel obstructive.
  • The routine: "I have a new phone" is among the commonest genuine help-desk requests.
  • Authority, weakly, and liking: a colleague in difficulty, and the help desk exists to help.

Question 2: what reconnaissance? The employee's name and role (professional networking site), the employee-number format (possibly a photograph of a badge, or a document's metadata), the date of birth (social media), and the password (a third-party breach, exploited through reuse). Note how little of this came from the company's own systems.

Question 3: which control failed? Two, and both should be named. First, the help desk's identity verification relied on information that is not secret: name, employee number and date of birth are all discoverable, so the procedure verified knowledge of public facts rather than identity. Second, the second factor could be reset by a telephone call, which means the strength of the second factor was reduced to the strength of the help-desk procedure. A third, upstream: password reuse was possible because there was no check against known-breached credentials.

Question 4: the single control. A stronger identity-verification procedure for second-factor resets: verification through the employee's manager, a video call with an identity document, or a code sent to a pre-registered alternative channel. Most simply, the reset should not be completable in one telephone call by someone who knows only public facts.

Question 5: what would have limited the damage? Alerting on second-factor re-enrolment followed by a sign-in from a new device and an unfamiliar location, and requiring re-authentication for sensitive actions so that a session obtained this way could not immediately do the most damaging things.

The lesson, and it is the most transferable in this chapter: a control is only as strong as its recovery path. An organisation that deploys multi-factor authentication and leaves a telephone call as the reset route has moved the attack, not prevented it. Attackers always look for the recovery path, because it exists precisely to let someone in who cannot authenticate normally.

A worked example: the analysis as a reproducible table

For the examination, this is the shape to produce for any scenario given:

QuestionCase one (supplier payment)Case two (help desk)
LeversThe routine, familiarity, mild authority; deliberately no urgencyUrgency, the routine, liking
ReconnaissanceSupplier relationship, invoice number, clerk's address; likely a compromised mailboxName, role, employee number, date of birth, reused password from a breach
Control that failedNo independent verification of a change of bank detailsIdentity verification using non-secret facts; second factor resettable by phone call
Single control that stops itCallback to a number already on file before any payment-detail changeStronger verification for second-factor reset; not completable on one call
What limits damageAlert on payments to recently changed detailsAlert on re-enrolment plus new-device sign-in; re-authentication for sensitive actions
munotes.in153

A Worked Case: Analysing a Real Attack

What beginners get wrong

  • Ending the analysis at "the employee was careless". It is hindsight, it produces no fix, and in both cases above the employee was doing their job correctly under the procedures they had.
  • Naming the technique and stopping. "This was phishing" is a classification, not an analysis. The four questions are the analysis.
  • Recommending "more training" as the single control. Training lowers the rate and cannot be the answer where, as in case one, there was nothing to notice. Name a process gate or a technical control.
  • Missing the recovery path. Case two is the standard shape: the control was sound and its reset route was not.
  • Listing twenty recommendations equally. Ranking is the professional contribution. Name the one that would have stopped it.
  • Forgetting the damage-limiting question. Prevention fails eventually; detection speed determines the loss.

Quick revision

  • The method, four questions: which lever, what reconnaissance, which control failed, what single control would have stopped it; plus a fifth, what would have limited the damage.
  • Case one, supplier payment fraud: the routine and familiarity, no urgency needed; likely a compromised mailbox supplied the invoice detail; no independent verification of banking changes; callback to a number already on file defeats it; alerting on recently changed payment details limits it.
  • Case two, help-desk second-factor reset: urgency and the routine; public facts plus a reused breached password; verification by non-secret facts and a resettable second factor; stronger reset verification defeats it; alerting on re-enrolment plus new-device sign-in limits it.
  • Two transferable lessons: the costliest attacks are often the least dramatic, and a control is only as strong as its recovery path.
  • An analysis that ends in blame has not finished; it must end in a control.

Test yourself

  1. State the four questions that constitute an analysis of a social-engineering incident.

Which psychological lever or levers were pulled; what reconnaissance made the approach plausible and where it came from; which control failed or was absent, stated precisely; and what single control would most likely have prevented it. A fifth question, what would have limited the damage, completes it.

  1. In the supplier-payment case, why would awareness training have been an inadequate recommendation?
munotes.in154

A Worked Case: Analysing a Real Attack

Because there was nothing for the clerk to notice: the request was routine, unhurried, referenced a genuine invoice number and came from a real supplier relationship, so no amount of alertness reliably distinguishes it. The effective control is procedural, a mandatory callback to a number already on file before payment details can change.

  1. What general lesson does the help-desk case teach about multi-factor authentication?

That a control is only as strong as its recovery path. Deploying a second factor while permitting it to be reset on a single telephone call, verified against facts that are publicly discoverable, reduces the strength of the second factor to the strength of the help-desk procedure and relocates the attack rather than preventing it.

  1. Why did the attacker in the supplier case deliberately not use urgency?

Because the request was already routine and therefore unlikely to be questioned, whereas urgency is itself a recognised warning sign and might have prompted the clerk to check. The absence of pressure made the message more, not less, convincing.

  1. Why must an analysis end in a control rather than in a judgement about the person deceived?

Because the individual was performing their normal duties under the procedures provided, so attributing the failure to them yields no improvement and discourages reporting. Identifying the missing process gate or technical control produces a change that prevents recurrence regardless of who is at the desk.

Contents This chapter on its own page

munotes.in155

Chapter Thirty-Three

Defences: Awareness, Verification and Multi-Factor

Syllabus topic Module 1, "Social Engineering and Human Exploitation Techniques"; Course Outcome 5, "Recommend appropriate mitigation strategies"

In one line

Because the target is a person doing their job, the defence cannot be "be more careful". It is a layered arrangement: train people to recognise the levers, build process gates that do not bend, and deploy multi-factor authentication so that a deception that succeeds still does not grant access.

In examination wording: mitigation of social engineering combines awareness training to improve recognition, procedural controls requiring independent verification of sensitive actions, technical controls including multi-factor authentication and least privilege to limit what a successful deception achieves, and detection and response arrangements, notably a blame-free reporting channel, to limit damage when prevention fails.

The principle that orders everything

State it first, because the rest follows from it: a control that depends on every person being alert every time will fail, because the attacker needs one person to be tired once.

So defences are ranked by whether they still work when somebody is deceived:

  1. Controls that do not involve the person's judgement at all (a process gate, a second factor) work regardless.
  2. Controls that limit the damage once someone is deceived (least privilege, rapid detection) work often.
  3. Controls that improve the person's judgement (training) reduce the rate and cannot eliminate it.

All three are needed. The mistake is to invest in the third and call it a programme.

Awareness training: necessary, insufficient, and often done badly

What it should teach. The levers, not a catalogue of current scams. A person who knows that manufactured urgency combined with a reason not to verify is the shape of an attack can recognise a technique they have never seen. A person who has memorised that "phishing emails have spelling mistakes" is worse than untrained, because they have a false test that today's attacks pass.

What it should include, concretely:

  • The organisation's own statements of what it will never ask for: no one will ask for your password, no one will ask you to read out a one-time code, IT will never ask you to disable a security control.
  • The specific high-risk actions and their rules: payment changes, credential entry, granting access, approving authentication prompts.
  • How to report, with a route that takes seconds.
  • That reporting a mistake is expected and will not be punished, stated by senior management, not buried in a policy.

Simulated phishing, used well and badly. Used well it measures susceptibility, identifies which departments and which lures need attention, and gives immediate teaching at the moment of the click. Used badly it becomes a trap: punitive consequences, humiliating league tables, or lures that exploit personal anxieties such as fake bonus or redundancy notices. Badly run programmes reduce security, because staff learn that the security team is adversarial and stop reporting real incidents. The metric to watch is not only the click rate but the reporting rate, which should rise; an organisation where clicks fall and reports also fall has taught people to stay quiet.

munotes.in156

Defences: Awareness, Verification and Multi-Factor

The honest limit. Training reduces susceptibility measurably and never to zero. Security professionals who research phishing are phished. Any programme whose success depends on a zero click rate is designed to fail.

Process gates: the highest-value control

This is where the real protection is, and it is the answer to almost every case in the previous chapter.

A process gate is a rule that a particular sensitive action requires a specific verification step, regardless of who asks, how senior they are, or how urgent it is. Its power is that it removes the decision from the individual: the clerk does not have to judge whether the message is genuine, because the procedure requires the callback either way.

The actions that need gates:

ActionThe gate
Changing a supplier's or employee's bank detailsCallback to a number already held on file, never one supplied in the request
Payments above a threshold, or to new payeesSecond authoriser, independently
Password or second-factor reset for another personIdentity verification not based on publicly discoverable facts
Granting or elevating accessRequest from the manager of record through the ticketing system, not by message
Releasing personal or commercially sensitive dataVerified requester and a recorded lawful basis
Anything described as too urgent for the normal processThe gate applies especially here

Three design rules make gates work:

Independent channel. The verifying contact must be obtained independently, from records the organisation already holds. A number in the email signature verifies nothing, because the attacker wrote it.

No exceptions for seniority. A gate that a sufficiently senior person can override is a gate the attacker will impersonate that person to bypass. This must be endorsed publicly by senior management, or staff will not enforce it against them.

Urgency is not a reason to skip; it is a reason to apply. Since manufactured urgency is the attacker's principal tool, a procedure that relaxes under pressure inverts the defence.

Multi-factor authentication: the highest-value technical control

Against credential phishing, this is the single most effective measure available, because it breaks the link between "the attacker learned the password" and "the attacker has access".

The factors, which an examination may ask you to name: something you know (a password), something you have (a phone, a token, a security key), something you are (a fingerprint, a face). Genuine multi-factor authentication uses factors from different categories; a password plus a security question is two things you know, and is not multi-factor.

munotes.in157

Defences: Awareness, Verification and Multi-Factor

The methods are not equal, and the ranking matters:

  • SMS codes: the weakest. Vulnerable to SIM-swap attacks and to interception, and phishable, but far better than nothing.
  • Authenticator application codes: better, since there is no telephone network to attack, but still phishable: an attacker who relays the login in real time can ask the victim for the code and use it within its validity window.
  • Push approval: convenient, and vulnerable to fatigue attacks, where an attacker with the password sends repeated prompts until an irritated or confused user approves one. Number matching, which requires the user to type a number shown on the login screen, largely addresses this and should be enabled.
  • Phishing-resistant factors (security keys and platform authenticators using the standards behind them): the strongest, because the credential is bound to the legitimate site's identity and simply will not produce a valid response to a look-alike domain. This defeats even a real-time relay, which the other methods do not.

Where it must be applied. Everywhere that matters, and specifically on the paths attackers use: remote access and VPN, email, administrative accounts, cloud consoles and anything holding personal data. An organisation that enables it for staff and exempts executives has protected the wrong people.

The recovery path. The lesson from the previous chapter, repeated because it is the commonest failure: securing the login and leaving a weak reset route relocates the attack. The reset procedure must be at least as strong as the control it restores.

Limiting the damage

Prevention fails, so these determine the loss:

  • Least privilege. If the deceived account can reach little, the incident is small. This is the control that turns a compromise into an inconvenience.
  • Segmentation, so a foothold does not reach everything.
  • Rapid revocation, the ability to disable an account and terminate its sessions in minutes.
  • Detection: alerts on impossible travel, new-device sign-ins, second-factor re-enrolment, mailbox forwarding rules created (a classic post-compromise step for payment fraud), and payments to recently changed details.
  • A tested incident response plan, so the first hour is executed rather than improvised.

The reporting culture, which underpins all of it

Treat it as a control, because it is one. The damage from a successful attack is largely a function of time: a fraudulent payment recalled within the hour is often recoverable; credentials revoked in minutes limit what is reached.

That time depends entirely on somebody saying "I think I did something". Which means:

  • Reporting must take seconds (a button in the mail client, one number to call).
  • It must be blameless, stated explicitly and by senior people.
  • Reports must be acknowledged, or people stop making them.
  • Near misses should be reported too, because they reveal campaigns in progress.
munotes.in158

Defences: Awareness, Verification and Multi-Factor

An organisation that disciplines the person who clicked has bought a quieter incident log and a longer average time to detection.

A worked example

A company reviews its social-engineering posture after the supplier-payment case. The recommendations, ranked by effect:

  1. Process gate: bank-detail changes require a callback to a number already on file; no exceptions for seniority or urgency. Signed off publicly by the finance director.
  2. Multi-factor authentication on email and remote access, using phishing-resistant keys for finance and administrative staff, with a reset procedure requiring manager verification.
  3. Detection: alert on payments to details changed within thirty days, and on any mailbox rule that forwards externally.
  4. Least privilege review of the finance system, so that no single account can both change payee details and release payment.
  5. Training on the levers, with simulations measured on reporting rate as well as click rate, and explicitly non-punitive.
  6. Reporting: a one-click report button and a published commitment that no one is penalised for reporting.

Note the ordering. Training is fifth, not because it is unimportant but because items one to four protect the company even when training fails, and item one alone would have prevented the incident that prompted the review.

What beginners get wrong

  • Treating training as the programme. It reduces the rate; it cannot be the control where there was nothing to notice.
  • Running punitive phishing simulations. They suppress reporting, which lengthens response time and increases loss.
  • Measuring only the click rate. The reporting rate matters as much; if both fall, people have learned to stay silent.
  • Calling a password plus a security question multi-factor. Both are things you know.
  • Assuming all second factors are equivalent. SMS is weakest; application codes are phishable in a real-time relay; push is vulnerable to fatigue without number matching; only site-bound keys resist phishing.
  • Securing the login and not the reset. The recovery path must be as strong as the control.
  • Allowing seniority to override a gate. The attacker will impersonate exactly that seniority.

Quick revision

  • Ordering principle: a control that needs everyone alert every time will fail. Rank by whether the control works when someone is deceived.
  • Training teaches the levers, the organisation's "we will never ask" statements, the high-risk actions, and how to report; simulations must be non-punitive and measured on reporting rate as well as clicks. It lowers the rate, never to zero.
  • Process gates are the highest-value control: independent-channel verification for bank-detail changes, large or new payments, password and second-factor resets, access grants and data releases; no exception for seniority, and urgency is a reason to apply the gate, not to skip it.
  • Multi-factor authentication: factors from different categories (know, have, are). SMS weakest; app codes phishable in real time; push needs number matching; site-bound security keys are phishing-resistant. Apply to email, remote access and administrative accounts, and secure the reset path.
  • Damage limitation: least privilege, segmentation, rapid revocation, detection (impossible travel, new devices, re-enrolment, forwarding rules, changed payee details), and a tested response plan.
  • A fast, blameless reporting culture is a control, because loss is a function of time.
munotes.in159

Defences: Awareness, Verification and Multi-Factor

Test yourself

  1. Why can awareness training not be the primary defence against social engineering?

Because the attacker needs only one person to be deceived once, because knowing about a bias does not remove it, and because in the most damaging attacks the request looks entirely routine so there is nothing for an alert person to notice. Training lowers the rate, while process gates and multi-factor authentication work regardless of whether anyone was alert.

  1. What is a process gate, and what three design rules make one effective?

A rule that a sensitive action requires a specific verification step regardless of who asks or how urgent it is. It must use an independently obtained channel such as a number already held on file; it must have no exception for seniority, since the attacker will impersonate exactly that seniority; and urgency must trigger the gate rather than excuse it, because manufactured urgency is the attacker's principal tool.

  1. Name the three categories of authentication factor and explain why a password plus a security question is not multi-factor.

Something you know, something you have, and something you are. A password and a security question are both things you know, so an attacker who obtains them by the same means, such as a phishing page or research, defeats both; genuine multi-factor authentication requires factors from different categories.

  1. Rank the common second-factor methods by resistance to phishing and explain the strongest.

SMS is weakest (SIM swap, interception, phishable); authenticator application codes are better but still phishable through a real-time relay; push approval is vulnerable to fatigue attacks unless number matching is enabled; security keys and platform authenticators are phishing-resistant because the credential is cryptographically bound to the legitimate site's identity and will not produce a valid response to a look-alike domain.

  1. Why is a blameless reporting culture treated as a security control, and what does punishing a click cost an organisation?

Because loss depends largely on elapsed time: a fraudulent payment recalled within the hour is often recoverable and credentials revoked in minutes limit what an attacker reaches, and that speed depends on someone reporting immediately. Punishing clicks makes people conceal mistakes, lengthening detection and response time and increasing loss, while also suppressing the near-miss reports that reveal campaigns in progress.

Contents This chapter on its own page

munotes.in160

Chapter Thirty-Four

Email Authentication: SPF, DKIM and DMARC

Syllabus topic Module 1, "Social Engineering and Human Exploitation Techniques"; Course Outcome 5, "Recommend appropriate mitigation strategies"

In one line

SPF says which servers may send mail for a domain. DKIM signs messages so tampering and forgery are detectable. DMARC ties those checks to the address the recipient actually sees, and tells receivers what to do when they fail.

In examination wording: Sender Policy Framework publishes, in DNS, the hosts authorised to send mail for a domain; DomainKeys Identified Mail attaches a cryptographic signature to a message, verifiable against a public key published in DNS; Domain-based Message Authentication, Reporting and Conformance requires that a passing SPF or DKIM result align with the domain in the visible From address, specifies the policy a receiver should apply on failure, and provides reporting.

The problem these solve

Email was designed without authentication. A sending server states who the mail is from, and historically the receiving server believed it. Anyone could send a message claiming to be from any address, which is why domain spoofing became the backbone of phishing.

These three mechanisms retrofit authentication. None of them assesses whether a message is honest; they establish whether it was authorised by the domain it claims. A message that passes all three may still be a phishing message sent from a domain the attacker registered legitimately, which is the limit stated honestly at the end of this chapter.

Two different "from" addresses

This distinction must come first, because SPF and DMARC differ precisely on it and no student can reason about alignment without it.

Every email has two sender addresses:

  • The envelope sender (also called the return-path or MAIL FROM), used by mail servers to route bounces. The recipient never sees it.
  • The header From, which is what the mail client displays. This is what the human reads and trusts.

They are normally the same domain, and there is no requirement that they be. An attacker can set an envelope sender at a domain they control, pass SPF for that domain honestly, and put the victim's bank in the header From. SPF alone is satisfied and the recipient sees a perfect forgery. That gap is exactly why DMARC exists.

SPF: who may send

What it is. A TXT record listing the servers permitted to send mail for the domain: specific addresses, ranges, and includes that pull in a provider's own list.

How it is checked. The receiving server takes the envelope sender's domain, looks up its SPF record, and asks whether the connecting server's IP address is authorised. The result is pass, fail, softfail, neutral or an error.

What it does well. It stops an arbitrary server sending mail with your domain in the envelope sender, which blocks a large volume of crude forgery.

Its three weaknesses, all examinable:

munotes.in161

Email Authentication: SPF, DKIM and DMARC

  1. It authenticates the envelope sender, not the visible From. By itself it does nothing about what the user sees.
  2. It breaks on forwarding. When a message is forwarded, the forwarding server relays it from an address that is not in the original domain's SPF record, so SPF fails for legitimate mail. This is the main reason SPF alone cannot be enforced strictly.
  3. It has a lookup limit. The specification caps the number of DNS lookups a record may require (ten), and organisations that add many providers exceed it, which makes the record permanently fail for everyone. This is a common real finding, and it is caused by adding services over the years without pruning.

The reconnaissance angle, from the DNS chapter: an SPF record is a published list of the organisation's mail-sending suppliers, and stale entries authorise systems nobody controls any more. Prune it.

DKIM: was it altered, and did the domain sign it

What it is. The sending server computes a cryptographic signature over selected headers and the body, and attaches it. The corresponding public key is published in DNS at a selector name the signature specifies.

How it is checked. The receiver reads the signature header, fetches the public key from the signing domain's DNS, and verifies. A pass means the message was signed by someone holding the private key for that domain and that the signed parts have not been altered in transit.

What it does well. Unlike SPF it is tied to the message rather than the connection, so it survives forwarding in most cases, which is why DMARC can be enforced at all.

Its weaknesses.

  • It proves the signing domain, which again need not be the visible From. Alignment is still required.
  • A short or old key weakens it, so keys should be at least 2048 bits and rotated.
  • Some mailing lists modify messages in ways that break the signature, which is why mailing lists and DMARC interact awkwardly.

DMARC: alignment, policy and reporting

DMARC is the one that makes the other two meaningful, and it contributes three things.

1. Alignment. DMARC requires that a passing SPF or DKIM result be for a domain that matches the domain in the header From, the one the user sees. This closes the gap described above: an attacker who passes SPF for their own domain while displaying yours now fails DMARC, because the authenticated domain and the displayed domain do not align.

Alignment may be relaxed (a subdomain matches the organisational domain) or strict (exact match). Relaxed is the practical default.

A message passes DMARC if either SPF or DKIM passes and aligns. Either is enough, which is what lets legitimate forwarded mail survive on DKIM when SPF has broken.

munotes.in162

Email Authentication: SPF, DKIM and DMARC

2. Policy. The record states what a receiver should do with mail that fails:

  • p=none: do nothing, just report. This is monitoring mode, and it is where every deployment starts.
  • p=quarantine: treat as suspicious, typically deliver to the spam folder.
  • p=reject: refuse the message outright, so it never reaches the user.

A policy of none is the single most common finding in this area. It means the organisation publishes DMARC, appears to be protected, and in fact forged mail is still delivered. As the DNS chapter noted, an attacker reads the policy before deciding whether domain spoofing is worth attempting, so none is an invitation.

3. Reporting. Aggregate reports are sent to an address in the record, listing which servers sent mail claiming the domain and whether they passed. This is what makes deployment possible: before enforcing, an organisation uses the reports to discover every legitimate sender, including the marketing platform and the ticketing system that nobody told the mail administrator about, and to fix their authentication.

Deploying them, in the right order

The sequence matters because enforcing too early blocks your own mail.

  1. Publish SPF listing known senders, and stay within the lookup limit.
  2. Enable DKIM signing on every sending system, with adequate key length.
  3. Publish DMARC with p=none and a reporting address.
  4. Read the reports for weeks. Identify every legitimate sender; some will be surprises. Fix their SPF or DKIM.
  5. Move to p=quarantine, perhaps applying to a percentage of mail first.
  6. Move to p=reject once the reports show legitimate mail passing consistently.

Two additions worth naming: BIMI, which can display a brand logo for messages that pass DMARC at enforcement, giving a commercial incentive to reach p=reject; and MTA-STS with TLS-RPT, which address a different problem, ensuring mail is delivered over TLS rather than downgraded, and are often recommended alongside.

What these do not do, stated honestly

This is the part most notes omit, and an examiner rewards it.

They authenticate the domain, not the intent. A message that passes all three may still be phishing, sent from a domain the attacker registered and configured properly. Authentication proves authorisation, not honesty.

They do not protect against look-alike domains. If the attacker sends from a domain one character different from yours, they are sending from their own domain and can pass SPF, DKIM and DMARC for it perfectly. Your DMARC policy governs your domain and says nothing about theirs. Look-alike domains are addressed by different measures: defensive registration of near-miss spellings, monitoring for newly registered similar domains, and receiver-side detection.

They do not protect a compromised account. Mail sent from a genuinely compromised mailbox is genuinely authorised, passes everything, and is the hardest form of the attack.

munotes.in163

Email Authentication: SPF, DKIM and DMARC

They do not stop display-name abuse. An attacker can set the display name to a trusted person's name while sending from an unrelated address that passes authentication for its own domain. Phone clients showing only the display name are particularly exposed, which is why some organisations tag external mail with a visible warning.

So the honest summary: these three make domain spoofing substantially harder, which removes one large category of phishing. They leave look-alike domains, compromised accounts and display-name abuse, which is why the procedural and multi-factor defences of the previous chapter remain necessary.

A worked example

An assessor reviews a company's email authentication.

ObservationFinding
SPF record present, listing seven includesExceeds the ten-lookup limit, so SPF permanently errors; must be consolidated
Two of the seven are services no longer usedStale authorisations; a supplier nobody controls may send as the company
DKIM signing enabled on the main provider onlyMarketing platform sends unsigned; will fail DMARC when enforced
DMARC published with p=noneForged mail is delivered; the domain is spoofable despite appearing protected
No reporting address configuredThe organisation cannot see who is sending as it, so cannot progress to enforcement
No external-mail tagging in the clientDisplay-name abuse is unmitigated

Recommendations in order: fix the SPF lookup overflow and remove stale entries; enable DKIM on every sending system; add a DMARC reporting address and analyse for several weeks; progress none to quarantine to reject; register or monitor the obvious look-alike domains; and tag external mail visibly, since authentication cannot address display-name abuse.

The finding that matters most is the combination of the first and fourth rows: the company believed it had email authentication, and in practice its SPF was erroring and its policy was doing nothing. Publishing the records is not the same as being protected, and the reports are what tell you which you have.

What beginners get wrong

  • Thinking SPF alone stops spoofing. It authenticates the envelope sender, which the user never sees. Without DMARC alignment, the visible From can still be forged.
  • Not knowing there are two From addresses. Alignment cannot be understood without it, and it is the examinable core of DMARC.
  • Leaving DMARC at p=none indefinitely. It reports and protects nothing; the domain remains spoofable.
  • Enforcing before reading reports. This blocks legitimate senders nobody had catalogued and gets the policy rolled back.
  • Believing DMARC stops look-alike domains. It governs only your domain; an attacker's own domain can pass its own checks.
  • Letting the SPF record grow past the lookup limit. It then fails for everyone, and it is a frequent real finding.
  • Assuming a passing message is trustworthy. Authentication proves authorisation, not intent.
munotes.in164

Email Authentication: SPF, DKIM and DMARC

Quick revision

  • Two sender addresses: the envelope sender (routing, invisible) and the header From (displayed, trusted). SPF checks the first; DMARC requires alignment with the second.
  • SPF: a TXT record of authorised sending hosts. Breaks on forwarding; capped at ten DNS lookups, and exceeding it makes it fail entirely.
  • DKIM: a cryptographic signature over headers and body, public key in DNS at a selector; survives forwarding; use 2048-bit keys and rotate.
  • DMARC: requires SPF or DKIM to pass and align with the visible From; sets policy none (monitor), quarantine, or reject; provides aggregate reports.
  • Deployment order: SPF, DKIM, DMARC at none, read reports and fix senders, then quarantine, then reject.
  • Limits: they do not stop look-alike domains, compromised accounts, or display-name abuse, and they prove authorisation rather than honesty.

Test yourself

  1. What are the two sender addresses in an email, and why does the distinction matter?

The envelope sender, used for routing and bounces and never shown to the user, and the header From, which the mail client displays. It matters because SPF authenticates the envelope sender, so an attacker can pass SPF for a domain they control while displaying a victim's domain; DMARC's alignment requirement is what closes that gap.

  1. What does DMARC add that SPF and DKIM do not provide on their own?

Alignment, requiring that a passing SPF or DKIM result be for a domain matching the visible From address; a policy telling receivers whether to do nothing, quarantine or reject failing mail; and aggregate reporting, which reveals every system sending as the domain and makes safe enforcement possible.

  1. Why does SPF break on forwarding, and how does DMARC accommodate legitimate forwarded mail?

Because a forwarding server relays the message from an address not listed in the original domain's SPF record, so the SPF check fails. DMARC passes if either SPF or DKIM passes and aligns, and DKIM signatures are attached to the message and usually survive forwarding, so forwarded mail can still pass.

  1. Why is a DMARC policy of p=none a finding rather than a protection?

Because it instructs receivers to take no action on messages that fail authentication, so forged mail claiming the domain is still delivered. The organisation appears protected by publishing a record while remaining spoofable, and an attacker can read the policy and conclude that spoofing will work.

  1. Name three things email authentication does not defend against.

Look-alike domains, since the attacker sends from a domain they own and can pass its own SPF, DKIM and DMARC; compromised genuine accounts, whose mail is properly authorised; and display-name abuse, where a trusted name is shown while the address belongs to an unrelated authenticated domain.

Contents This chapter on its own page

munotes.in165

Chapter Thirty-Five

TCP/IP for the Scanner: Layers, Addresses, Ports and Flags

Syllabus topic Module 1, "Network Scanning and Port Scanning Techniques: Understand TCP/IP behavior"

In one line

A scanner needs four things: the layers (so it knows what it is manipulating), the difference between an address and a port (a machine and a door), the difference between TCP and UDP (a conversation and a shout), and the TCP flags (the single-bit switches that every scan type varies).

In examination wording: the TCP/IP model organises communication into link, internet, transport and application layers; IP provides addressing and best-effort delivery between hosts; TCP provides connection-oriented, reliable, ordered delivery using a handshake, sequence numbers and control flags; UDP provides connectionless, unreliable datagram delivery; ports identify the service within a host.

Why a scanner needs this and a user does not

A person browsing the web never thinks about any of it, because the stack hides it. A scanner is doing the opposite of using the network normally: it is constructing packets that do not occur in ordinary traffic and reading what comes back, and the whole technique rests on the fact that the rules specify how a host must respond even to a packet that makes no sense.

So a scanner author, and a student who wants to understand rather than memorise, needs to know what the rules are. Everything in the next four chapters is "send something unusual and see what the rules force the target to do".

The layers

Four layers in the TCP/IP model, each adding a header to what the layer above handed it. The order and what each contributes:

LayerIts jobWhat a scanner cares about
ApplicationThe actual protocol: HTTP, DNS, SMTPBanner grabbing and version detection live here
TransportTCP or UDP; delivers to the right portThe layer nearly all scanning manipulates
InternetIP; delivers to the right host across networksAddresses, TTL (useful in fingerprinting), fragmentation
LinkThe local hop: Ethernet, Wi-Fi, using MAC addressesARP, which matters for local host discovery and sniffing

Encapsulation is the mechanism: your data is wrapped in a TCP header, that in an IP header, that in an Ethernet frame. Each layer reads and strips its own header at the far end. The practical consequence for this block is that a scanner writes the transport header itself rather than asking the operating system to make a normal connection, which is how it can set flag combinations no application would ever produce.

Two layer facts used later:

  • The link layer is local only. MAC addresses do not cross routers, which is why ARP-based host discovery works on your own segment and not remotely, and why ARP poisoning is a local attack.
  • IP is best-effort. It does not guarantee delivery, order or duplication-freedom. Everything reliable is built above it, in TCP.
munotes.in166

TCP/IP for the Scanner: Layers, Addresses, Ports and Flags

Addresses and ports: the building and the doors

An IP address identifies a host. A port identifies which service on that host, a 16-bit number, so 0 to 65535.

The analogy that holds: the address is the building, the port is the door. A packet needs both, and a scanner's question is precisely "which doors are open?"

Ranges to know:

  • 0 to 1023, well-known ports, conventionally assigned to standard services and on many systems requiring privilege to bind.
  • 1024 to 49151, registered ports, used by particular applications.
  • 49152 to 65535, dynamic or ephemeral ports, used as the source port for outgoing connections.

That last group explains something students find confusing: every connection has two ports, a source and a destination. Your browser connecting to a web server uses destination port 443 and some arbitrary high source port, and the server's reply is addressed back to that source port. A firewall that permits return traffic must therefore track which conversations are in progress, which is the difference between a stateless and a stateful firewall and matters in the firewall chapter.

Ports worth recognising, because service identification begins with an educated guess:

PortServiceWhy a tester notices
21FTPOften unencrypted, sometimes anonymous
22SSHRemote administration; a credential target
23TelnetUnencrypted remote administration; a serious finding
25, 465, 587SMTPMail; enumeration and relay checks
53DNSBoth TCP and UDP; zone transfers use TCP
80, 443HTTP, HTTPSThe largest application attack surface
110, 143, 993, 995POP3, IMAPMail retrieval
135, 139, 445Windows RPC and SMBFile sharing; should never face the internet
161SNMPUDP; default community strings
389, 636LDAPDirectory; user enumeration
1433, 3306, 5432SQL Server, MySQL, PostgreSQLDatabases exposed directly is a finding
3389RDPRemote desktop; heavily attacked

A port number is a convention, not a rule: a web server can listen on 8080 or 7777, which is why version detection probes rather than assuming.

TCP against UDP

The two transport protocols behave differently, and the difference determines how each is scanned.

TCP is connection-oriented and reliable. Before data flows, the two ends perform a handshake; thereafter, sequence numbers order the bytes, acknowledgements confirm receipt, and lost segments are retransmitted. The protocol therefore has a defined response to every situation, including nonsensical ones, and that definiteness is what makes TCP scanning informative.

UDP is connectionless and unreliable. A datagram is sent; there is no handshake, no acknowledgement, no retransmission and no ordering. It suits things that prefer speed over perfection, DNS queries, time synchronisation, streaming media, and many network services.

The consequence for scanning, previewed here and taken up properly later: TCP gives an unambiguous answer (a SYN gets SYN/ACK if open or RST if closed), whereas UDP usually gives silence when open, since a service that receives a datagram it does not understand may simply ignore it. Silence is also what a firewall produces. So UDP scanning is slow, ambiguous and frequently skipped, which is exactly why services that live on UDP are often less examined and worth a tester's attention.

munotes.in167

TCP/IP for the Scanner: Layers, Addresses, Ports and Flags

The TCP flags

Six control bits in the TCP header. Every scan type in the next chapters is a different combination of them, so learn what each means.

FlagNameMeaning
SYNSynchroniseStart a connection; synchronise sequence numbers
ACKAcknowledgeThis packet acknowledges data received; the acknowledgement field is meaningful
FINFinishI have no more data; begin an orderly close
RSTResetAbort. Something is wrong, or nothing is listening
PSHPushDeliver this to the application now rather than buffering
URGUrgentThe urgent pointer field is meaningful

Two of these do nearly all the work in scanning:

SYN is the only flag that opens a connection, so it is how a scanner asks "is anyone there?"

RST is the protocol's way of saying "no". A closed port answers with RST. A host receiving a packet for a connection it does not have answers with RST. Recognising that RST means refusal is most of what is needed to read a scan's results.

PSH and URG are not used for scanning logically; they appear in the XMAS scan simply because setting them alongside FIN produces a packet with several flags lit, which is where the name comes from.

Two more fields matter later:

  • The sequence number orders bytes and is what an attacker attempting session prediction would need to guess, which appears in the session-hijacking chapter.
  • The window size, along with the IP header's TTL and other defaults, varies between operating systems, and the pattern of those defaults is what operating-system fingerprinting reads.

ICMP, the third protocol a scanner meets

ICMP is not a transport protocol; it carries control and error messages for IP. A scanner meets it constantly:

  • Echo request and reply are ping, the simplest host-discovery method.
  • Destination unreachable messages report problems, and the code matters. Port unreachable is the signal that a UDP port is closed, and is the only positive information a UDP scan usually gets. Administratively prohibited indicates a firewall is rejecting rather than silently dropping, which the firewall-detection chapter uses.
  • Time exceeded is what makes traceroute work, by sending packets with increasing TTL and noting which router reports the expiry.

Many networks block inbound ICMP, which is why "it does not respond to ping" does not mean "it is not there", a point the host-discovery chapter develops.

munotes.in168

TCP/IP for the Scanner: Layers, Addresses, Ports and Flags

A worked example: reading one exchange

A scanner sends a TCP packet to 203.0.113.10 port 22 with only the SYN flag set, from source port 51344.

What is in the packet, layer by layer: an Ethernet frame addressed to the local router's MAC; an IP header with source and destination addresses and a TTL; a TCP header with source port 51344, destination port 22, an initial sequence number, and the SYN flag set alone.

What the rules force, depending on the target's state:

Target stateResponseWhat the scanner concludes
A service is listening on 22SYN/ACKOpen
Nothing is listening on 22RST (usually with ACK)Closed: the host is alive but has no service there
A firewall drops the packetnothingFiltered: state unknown
A firewall rejects itICMP administratively prohibitedFiltered, and a firewall is confirmed

Four possible outcomes, each forced by the specification rather than chosen by the target, and each telling the scanner something different. That table is port scanning in miniature, and the next chapter builds every scan type from it.

What beginners get wrong

  • Confusing an address with a port. The address selects the host, the port selects the service on it. Both are needed and they come from different layers.
  • Forgetting the source port. Every connection has two ports; the ephemeral source port is why stateful firewalls must track conversations.
  • Assuming a port number identifies the service. It is a convention; services can listen anywhere, which is why version detection probes.
  • Expecting UDP to behave like TCP. There is no handshake, so an open UDP port usually says nothing, and silence is ambiguous between open and filtered.
  • Reading no reply as "the host is down". Many networks drop ICMP and unsolicited packets; absence of a reply is absence of information.
  • Treating RST as an error. It is the protocol's normal way of refusing, and it is the most informative response a scanner receives.

Quick revision

  • Layers: application (banners and versions), transport (TCP/UDP and ports, where scanning happens), internet (IP addresses, TTL, best-effort), link (MAC, ARP, local only).
  • Address selects the host, port selects the service (0 to 65535: well-known 0 to 1023, registered to 49151, ephemeral above, used as source ports).
  • TCP: connection-oriented, reliable, handshake and sequence numbers, and a defined response to every situation, which is what makes scanning informative. UDP: connectionless and unreliable, so an open port usually stays silent and results are ambiguous.
  • Flags: SYN (open a connection), ACK (acknowledges), FIN (orderly close), RST (refusal, the key signal), PSH and URG (delivery hints, used in XMAS only to light several flags).
  • ICMP carries control and errors: echo for ping, port unreachable as the only positive UDP signal, administratively prohibited revealing a rejecting firewall, time exceeded for traceroute. Inbound ICMP is often blocked.
  • One SYN yields four outcomes: SYN/ACK (open), RST (closed), silence (filtered), ICMP prohibited (filtered, firewall confirmed).
munotes.in169

TCP/IP for the Scanner: Layers, Addresses, Ports and Flags

Test yourself

  1. Distinguish an IP address from a port, and say which layer each belongs to.

An IP address identifies a host and belongs to the internet layer; a port is a 16-bit number identifying the service within that host and belongs to the transport layer. A packet needs both to reach a specific service on a specific machine.

  1. Why does TCP give a scanner clearer information than UDP?

Because TCP is connection-oriented with a specification that defines a response to every situation, including malformed or out-of-sequence packets: an open port answers a SYN with SYN/ACK and a closed port with RST. UDP is connectionless, so an open port commonly returns nothing at all, making silence ambiguous between open and filtered.

  1. Name the six TCP flags and say which two carry most of the meaning in scanning.

SYN, ACK, FIN, RST, PSH and URG. SYN carries most meaning because it is the only flag that opens a connection and so is how a scanner asks the question; RST carries the rest because it is the protocol's refusal, returned by a closed port or for a connection that does not exist.

  1. What are the four possible outcomes of sending a bare SYN to a port, and what does each mean?

SYN/ACK means a service is listening, so the port is open; RST means the host is alive but nothing is listening, so the port is closed; no reply means a firewall silently dropped the packet, so the port is filtered and its state unknown; an ICMP administratively-prohibited message means a firewall rejected it, so the port is filtered and a firewall is confirmed.

  1. Why does "no response to ping" not establish that a host is absent?

Because many networks block inbound ICMP echo requests at the perimeter, so a live, fully functioning host may simply never answer. Absence of a reply is absence of information, which is why host discovery uses TCP and UDP probes as well as ICMP.

Contents This chapter on its own page

munotes.in170

Chapter Thirty-Six

The Three-Way Handshake, and Why Scanning Works

Syllabus topic Module 1, "Network Scanning and Port Scanning Techniques: Understand TCP/IP behavior and scanning methodologies"

In one line

TCP opens a connection with three packets: SYN, then SYN/ACK, then ACK. Port scanning works because the standard forces a host to answer the first packet differently depending on whether anything is listening, and that single difference is all the information a scanner needs.

In examination wording: the TCP three-way handshake establishes a connection through an exchange in which the initiator sends a segment with the SYN flag set, the responder replies with SYN and ACK if a service is listening or with RST if not, and the initiator completes the connection with ACK; port scanning exploits this specified behaviour to infer the state of a port from the response to a crafted segment.

Why a handshake exists at all

IP is best-effort: packets may be lost, duplicated, delayed or reordered. TCP promises reliable, ordered delivery on top of that, and to keep the promise both ends must agree, before any data moves, on where the numbering starts.

The handshake does three things:

  1. Confirms both ends are present and willing. A service must be listening and must accept the connection.
  2. Exchanges initial sequence numbers. Each side chooses a starting number and tells the other, so that subsequent bytes can be ordered and acknowledged. Each side must learn the other's number, which is why it takes three packets rather than two.
  3. Confirms the return path works. By the time the third packet arrives, each side has received something from the other, so two-way reachability is established.

The third point is the reason a handshake also functions as proof that the client's address is real, which is exactly what the SYN flood later abuses.

The three packets

Take a client opening a connection to a web server on port 443.

Packet 1, client to server: SYN. The client sends a segment with the SYN flag set and its initial sequence number, say x. It says: I want to start, and my numbering begins at x.

At this moment the client's connection state is SYN-SENT.

Packet 2, server to client: SYN and ACK. If a service is listening and accepts, the server replies with both flags set. The ACK acknowledges the client's SYN, carrying x + 1 as the next byte it expects. The SYN carries the server's own initial sequence number, say y. It says: agreed, I received your x, and my numbering begins at y.

The server's state is now SYN-RECEIVED, and, importantly, the server has allocated resources for a connection that is not yet established. This is the half-open state.

Packet 3, client to server: ACK. The client acknowledges the server's SYN with y + 1. Both ends are now ESTABLISHED and data may flow.

munotes.in171

The Three-Way Handshake, and Why Scanning Works

Why the SYN and the ACK can share packet 2 is worth stating: they are independent bits in the same header, so the server acknowledges and initiates simultaneously. That is why the exchange is three packets and not four.

The other outcome: RST

If nothing is listening on the port, the standard requires the host to reject the attempt, and it does so by replying with RST (usually RST with ACK). It says: there is nothing here, do not continue.

And that is the whole basis of port scanning:

The host's situationIts required reply to a SYN
A service is listeningSYN/ACK
No service is listeningRST

Two different, unambiguous, mandatory responses. The target is not choosing to inform the scanner; the specification requires it to answer this way so that ordinary connections work. A host that stopped answering would break every legitimate client.

Why that is enough

Everything else follows from those two lines.

To find open ports, send a SYN to each port and record which reply with SYN/ACK. That is a SYN scan, and it is the reason port scanning is fast and reliable rather than a matter of guesswork.

To avoid completing connections, send the SYN, read the reply, and if it is SYN/ACK send RST instead of the final ACK. The connection never reaches ESTABLISHED, so the application on the target may never be told a connection occurred, and historically it was not logged by the service. This is the half-open or SYN scan, and its "stealth" is exactly this and nothing more.

To fingerprint through firewalls, note that a third response exists that the table does not list: no reply at all. That cannot happen in a correctly functioning direct conversation, because the standard requires SYN/ACK or RST. So silence means something in between interfered, which is what "filtered" means and what the firewall-detection chapter reads.

To scan without opening connections at all, exploit a different rule. The specification also says what a host must do with a segment that arrives for a connection that does not exist: a closed port must reply RST, and an open port must ignore it. That single asymmetry is what FIN, NULL and XMAS scans use, and it is why those scans can probe without ever sending a SYN.

The examinable point: a scanner is not breaking anything. It is asking questions the standard obliges the target to answer, or sending packets the standard specifies a response to. Port scanning is a consequence of TCP being well specified.

The half-open state and what it costs the target

Dwell on packet 2 for a moment, because it matters twice more in this book.

munotes.in172

The Three-Way Handshake, and Why Scanning Works

When the server sends SYN/ACK it must remember the half-formed connection: the client's address and port, the sequence numbers, the options negotiated. It holds that in a finite structure, often called the backlog, and waits for the third packet. If the ACK never arrives, the entry sits there until a timeout expires, and the server may retransmit the SYN/ACK several times first.

Two consequences:

  • A SYN scan leaves the target holding half-open entries until they time out. A scan of many ports is therefore not free for the target, even though the scanner has done nothing wrong.
  • A deliberate flood of SYNs that are never completed fills the backlog, so genuine clients cannot connect. That is the SYN flood, the protocol denial-of-service attack of Module 2, and it is the handshake's cost turned into a weapon. The defence, SYN cookies, works by refusing to allocate the state at all until a valid ACK proves the client is real.

Closing a connection, briefly

For completeness, since FIN appears in the scan types. An orderly close is four packets, because each direction closes independently: one side sends FIN, the other ACKs it, then the other side sends its own FIN, which is ACKed. Either side may also abort at any time with RST, which is immediate and unacknowledged.

The point that matters for scanning: FIN is meaningful only within an existing connection. Sending a bare FIN to a port with no connection is nonsense, which is precisely why the standard's rule for nonsense packets is what the FIN scan exploits.

A worked example

A tester, with authorisation, probes three ports on one host and reads the exchanges.

Port 443. Sends SYN. Receives SYN/ACK. Concludes open, and immediately sends RST to tear down the half-open connection rather than completing it. The target briefly held a half-open entry and its web service was probably never informed.

Port 25. Sends SYN. Receives RST/ACK. Concludes closed: the host is alive and reachable, and no mail service is listening. Note that this is still useful, because it proves the host exists.

Port 3306. Sends SYN. Receives nothing, twice, after retransmission. Concludes filtered: since the standard requires one of the two answers, silence means an intermediate device dropped the packet. Whether a database is behind it is unknown.

Three ports, three distinct conclusions, all derived from two lines of the specification. And one further observation for the report: the mixture is itself informative. A host that returns RST on some ports and silence on others has a firewall with per-port rules; a host that returns silence on everything except two ports has a default-deny firewall, which is the reasoning the firewall chapter formalises.

munotes.in173

The Three-Way Handshake, and Why Scanning Works

What beginners get wrong

  • Thinking the handshake is four packets. It is three, because SYN and ACK are independent flags that can be set in the same segment.
  • Believing a half-open scan is undetectable. It avoids completing the connection, so the application may not log it, but the pattern of many SYNs without ACKs is exactly what a network sensor looks for.
  • Forgetting that a closed port is informative. RST proves the host is alive, which silence does not.
  • Treating no reply as "closed". Closed has a specific signal, RST. Silence means filtered, and the state is unknown.
  • Thinking scanning exploits a flaw. It uses required behaviour; a host that refused to answer would break normal connectivity.
  • Missing that half-open connections cost the target resources. That cost is what the SYN flood weaponises.

Quick revision

  • Three packets: SYN (client, sequence x), SYN/ACK (server, acknowledges x + 1, sends its own y), ACK (client, acknowledges y + 1). States: SYN-SENT, SYN-RECEIVED (half-open), ESTABLISHED.
  • The handshake confirms willingness, exchanges initial sequence numbers, and proves the return path works.
  • The basis of scanning: a SYN to an open port must be answered SYN/ACK; to a closed port, RST. Both are mandatory, so the target cannot decline to inform the scanner.
  • A third outcome, silence, is impossible in a direct exchange and therefore means an intermediate device dropped the packet: filtered.
  • A second rule, that a segment for a non-existent connection gets RST from a closed port and is ignored by an open one, is what FIN, NULL and XMAS scans use.
  • The server allocates state at SYN-RECEIVED; scanning leaves half-open entries, and flooding them deliberately is the SYN flood, answered by SYN cookies.
  • Closing is four packets (FIN and ACK each way), or an immediate RST. FIN is meaningful only inside an existing connection.

Test yourself

  1. Describe the three-way handshake, naming the flags and what each packet accomplishes.

The client sends a segment with SYN set and its initial sequence number; the server, if a service is listening, replies with SYN and ACK together, acknowledging the client's number and supplying its own; the client replies with ACK acknowledging the server's number, after which the connection is established. It confirms mutual willingness, exchanges initial sequence numbers and proves the return path works.

  1. Why is port scanning possible at all, and why is it not an exploitation of a flaw?

Because the TCP specification requires a host to answer a SYN with SYN/ACK when a service is listening and with RST when none is, so the response distinguishes open from closed. This is required behaviour that makes ordinary connections work; a host that refused to answer would be unable to serve legitimate clients.

munotes.in174

The Three-Way Handshake, and Why Scanning Works

  1. What does a complete absence of response indicate, and why can it not occur in a direct exchange?

It indicates the port is filtered, meaning an intermediate device such as a firewall silently discarded the packet, so the port's real state is unknown. It cannot occur directly because the standard requires either SYN/ACK or RST, so silence proves something intervened.

  1. What is the half-open state, what does it cost the target, and which attack weaponises it?

After sending SYN/ACK the server has allocated connection state and is waiting for the final ACK, which is the half-open or SYN-RECEIVED state. It consumes an entry in a finite backlog until it times out. Deliberately flooding a target with SYNs that are never completed fills that backlog so genuine clients cannot connect, which is the SYN flood.

  1. Why can a bare FIN sent to a port be used for scanning?

Because FIN is meaningful only within an existing connection, so a bare FIN refers to a connection that does not exist, and the specification dictates the response to such a segment: a closed port replies RST while an open port ignores it. That asymmetry lets a scanner infer state without ever sending a SYN.

Contents This chapter on its own page

munotes.in175

Chapter Thirty-Seven

Host Discovery: Finding What Is Alive

Syllabus topic Module 1, "Network Scanning and Port Scanning Techniques"

In one line

Before asking which ports are open, a scanner asks which addresses are alive. Ping is the obvious method and the one most often blocked, so real discovery uses several probes, and on a local network ARP is the one that cannot be refused.

In examination wording: host discovery, sometimes called a ping sweep, is the identification of active hosts within an address range prior to port scanning; it may use ICMP echo requests, TCP or UDP probes to common ports, ARP requests on the local segment, or other ICMP message types, and a non-response indicates only that no reply was received rather than that no host exists.

Why discovery is a separate step

Arithmetic makes the case. A modest internal range of 256 addresses, scanned across the full 65,535 TCP ports, is over sixteen million probes. If only twelve addresses are in use, more than ninety-five per cent of that work is spent on empty space, and on a firewalled network each probe to an empty address waits for a timeout that never resolves, which is the slowest possible failure.

So discovery is a cheap filtering step: identify the live addresses first, then spend the expensive port scan only on those.

For an assessor there is a second reason. The registry lookup of the WHOIS chapter gives the organisation's allocated range, which may be far larger than what is actually used. Discovery turns "the client owns 1,024 addresses" into "forty of them respond", which is the real scope of the engagement and the number that goes in the report.

ICMP echo: ping, and why it often fails

The simplest probe: send an ICMP echo request, expect an echo reply. A reply proves the host is up and reachable.

It is the first thing anyone tries and it is unreliable on the modern internet, because many organisations block inbound ICMP at the perimeter. The reasoning is that it reveals which addresses are in use and assists mapping, so blocking it is a small obscurity measure. Whether that is worthwhile is debatable, since the later probes find the hosts anyway, and blocking ICMP entirely breaks useful diagnostics and can interfere with path MTU discovery, which relies on ICMP messages to negotiate packet sizes; blocking it wholesale causes connections that establish and then hang.

The rule to remember: no reply to ping means no reply to ping. It does not mean the host is absent, and a scanner that stops there will miss most of a firewalled estate. This is the commonest error in the topic.

The other ICMP probes

ICMP offers more than echo, and a thorough sweep uses several because a firewall may block one type and not another:

munotes.in176

Host Discovery: Finding What Is Alive

  • Timestamp request, which asks a host for its clock. Some hosts answer it while echo is blocked.
  • Address mask request, older and rarely answered, but occasionally revealing.
  • Non-echo replies as evidence. Sending a packet to a host and receiving any ICMP error, such as destination unreachable, proves something is there to generate it, even though it is not the reply you asked for.

TCP probes: asking the handshake instead

Since ICMP is often blocked but services must be reachable to be useful, the reliable method is to use TCP, and the previous chapter supplies the logic.

TCP SYN probe. Send a SYN to a commonly open port (443, 80, 22, 445). By the handshake rules, an open port answers SYN/ACK and a closed one answers RST, and either response proves the host is alive. That is the key insight: for discovery you do not care which answer you get, only that you got one. A "closed" reply is a successful discovery.

TCP ACK probe. Send a bare ACK. A host with no matching connection must reply RST, so an RST proves it is alive. This is useful where a firewall blocks incoming SYNs but permits packets that look like established traffic, which stateless filters commonly do.

Choosing which ports to probe matters. Probing 443 and 80 finds web servers; adding 22 finds Linux hosts and 445 finds Windows hosts; adding 3389 finds machines offering remote desktop. A sweep using several well-chosen ports finds substantially more than one using a single port.

ARP: the probe that cannot be refused

On the local segment, there is a method no host firewall can ignore, and it is the most reliable discovery technique that exists.

IP is a layer above the link, so before one machine on a local network can send an IP packet to another it must learn the destination's MAC address. It does this with an ARP request, broadcast to the whole segment: "who has this IP address?" The owner must reply, because if it does not, no traffic can reach it at all.

Consequently a host on the same segment cannot hide from ARP while remaining usable. A host firewall can drop ICMP and every TCP probe and still must answer ARP, because ARP is how it receives anything.

An ARP sweep therefore finds every live host on the local network, quickly and definitively. Two limits: it works only on the local segment, because ARP does not cross routers, so it is an internal-testing technique; and it is noisy in the sense that it broadcasts, though ordinary network operation produces ARP traffic constantly.

The security reading, which points forward: because ARP has no authentication and hosts accept replies freely, the same protocol that makes discovery reliable also makes ARP poisoning possible, which is the man-in-the-middle chapter.

munotes.in177

Host Discovery: Finding What Is Alive

UDP probes

Sending a UDP datagram to a closed port normally produces an ICMP port-unreachable message, which proves the host is alive. Sending to an open port usually produces nothing, or a service-specific reply.

It is slower and less reliable than TCP discovery because hosts commonly rate-limit ICMP error generation, so responses are throttled. It is worth including for hosts that run only UDP services, and a probe to a well-known UDP port such as 53 or 161 sometimes elicits a service reply that both proves the host and identifies the service.

Other discovery routes

Reverse DNS. Look up the PTR record for each address in the range. This touches only DNS servers, not the hosts, so it is quiet, and it often returns descriptive names that reveal purpose even for hosts that never answer a probe.

Broadcast and multicast responses. On a local network, hosts announce themselves through discovery protocols for printers, file sharing and media devices, and simply listening for a while identifies many without sending anything.

Routing information. ICMP time-exceeded responses from traceroute reveal intermediate routers, which are themselves hosts and often forgotten in inventories.

Reading the results honestly

The output of discovery is a list of addresses in three states:

StateEvidenceWhat to do
UpAny reply at all: echo reply, SYN/ACK, RST, ICMP error, ARP replyProceed to port scanning
Down or filteredNo reply to any probeUnknown. Note it; do not record it as "no host"
UnreachableICMP host-unreachable from a routerThe route exists but the host does not answer on it

The middle row is where care is needed. A report that says "only 40 of 1,024 addresses are in use" is making a claim the evidence does not support; the defensible statement is "40 responded to the probes used; the remainder did not respond and may be absent, firewalled, or powered off". The distinction matters because a heavily firewalled but live host is exactly the kind of thing an assessment must not miss.

A worked example

Vikram is engaged to assess an internal network segment, and separately the organisation's external range.

Externally, against the allocated range of 256 addresses:

  • ICMP echo to all 256: no replies at all. The perimeter blocks ping.
  • TCP SYN to 443 and 80: nine hosts answer, seven with SYN/ACK and two with RST. All nine are alive; the two returning RST have no web service but exist.
  • TCP SYN to 22, 445 and 3389: two further hosts answer, one of which offers remote desktop, a finding in itself.
  • Reverse DNS across the range: names for fourteen addresses, including three that answered nothing. Those three are recorded as "named in DNS, unresponsive to probes", which is a finding worth following up because a name usually implies a host.
  • Result: eleven confirmed live, three suspected, 242 unknown.
munotes.in178

Host Discovery: Finding What Is Alive

Internally, on the local segment:

  • ARP sweep: sixty-three hosts, immediately and unambiguously, including nineteen that answer no ICMP and no TCP probe because their host firewalls drop everything. They cannot refuse ARP.

The contrast is the lesson. Externally he must infer from several probes and accept uncertainty; internally ARP gives a definitive answer. And the nineteen firewalled hosts that ARP found would have been invisible to every other method, which is why an internal assessment that relies on ping sweeps understates the estate badly.

What beginners get wrong

  • Treating no reply as "no host". It means no reply. Firewalls, host firewalls and powered-off machines all look identical from outside.
  • Relying on ping alone. Inbound ICMP is widely blocked; a ping sweep on a firewalled network finds almost nothing.
  • Forgetting that RST proves life. For discovery, a closed port is as good as an open one; any response establishes the host exists.
  • Skipping ARP on internal tests. It is the only probe a usable host cannot refuse, and it finds firewalled machines nothing else sees.
  • Expecting ARP to work remotely. It does not cross routers; it is a local-segment technique only.
  • Scanning every port on every address. Discovery exists to avoid wasting the overwhelming majority of the work on empty space.
  • Overstating the conclusion in the report. Say what responded to what, not how many hosts exist.

Quick revision

  • Discovery precedes port scanning to avoid spending the expensive scan on empty addresses, and it converts an allocated range into the real scope.
  • ICMP echo (ping) is simplest and widely blocked; no reply means no reply, not absence. Timestamp and address-mask requests, and any ICMP error received, are alternative evidence.
  • TCP SYN probes to common ports are the reliable external method: SYN/ACK or RST both prove the host is alive. TCP ACK probes elicit RST and pass some stateless filters.
  • ARP on the local segment cannot be refused by a usable host, so an ARP sweep is definitive internally; it does not cross routers. The same lack of authentication enables ARP poisoning later.
  • UDP probes rely on ICMP port-unreachable and are slowed by ICMP rate limiting.
  • Quiet routes: reverse DNS across the range, listening for local discovery-protocol broadcasts, and routers revealed by traceroute.
  • Report three states: up (with the evidence), no response (unknown), and unreachable. Do not claim absence.
munotes.in179

Host Discovery: Finding What Is Alive

Test yourself

  1. Why is host discovery performed before port scanning?

Because scanning every port on every address in a range spends the great majority of the effort on unused addresses, and on firewalled networks each probe to an empty address costs a full timeout. Discovery filters the range down to the addresses worth scanning, and for an assessor it converts an allocated range into the engagement's real scope.

  1. Why does a TCP SYN probe make a better discovery method than ping, and why does a closed port still count as a success?

Because inbound ICMP is widely blocked at perimeters while services must remain reachable, so TCP probes to common ports get through where ping does not. A closed port answers RST, and since the purpose of discovery is only to establish that something is there, any response, SYN/ACK or RST, proves the host is alive.

  1. Why can a host on the same network segment not hide from an ARP sweep?

Because ARP is how other machines learn the MAC address needed to deliver any IP traffic to it. A host that did not answer ARP requests could not receive traffic at all, so any usable host must reply, regardless of how restrictive its firewall is for ICMP and TCP.

  1. What are the limits of ARP-based discovery?

It works only on the local segment, because ARP is a link-layer protocol and does not cross routers, so it is available for internal testing and not for assessing a remote network.

  1. How should an assessor report addresses that responded to nothing?

As having produced no response to the probes used, with the probes named, rather than as absent hosts. A firewalled but live host, a powered-off machine and an unallocated address are indistinguishable from outside, and a live host that silently drops all probes is precisely what an assessment must not record as nonexistent.

Contents This chapter on its own page

munotes.in180

Chapter Thirty-Eight

The Scan Types: Connect, SYN, FIN, NULL and XMAS

Syllabus topic Module 1, "Network Scanning and Port Scanning Techniques: ... scanning methodologies including SYN, FIN, NULL, XMAS, and ACK scans"

In one line

Every TCP scan type is the same question asked with a different packet. Connect completes the handshake, SYN starts and abandons it, and FIN, NULL and XMAS send packets that fit no connection at all, relying on the rule that a closed port must object while an open one stays silent.

In examination wording: TCP port scanning techniques differ in the flag combination sent and therefore in the inference drawn, the traces left and the reliability of the result; connect and SYN scans exploit the handshake's mandated responses, while FIN, NULL and XMAS scans exploit the specified handling of segments that do not correspond to an existing connection.

The two rules everything is built from

Restated from the handshake chapter, because the entire chapter is their consequence.

Rule 1, the handshake. A SYN arriving at an open port must be answered SYN/ACK; arriving at a closed port it must be answered RST.

Rule 2, segments for no connection. A TCP segment that is not a SYN and does not belong to an existing connection must be answered RST by a closed port, and must be ignored by an open port.

Rule 1 gives a positive signal from open ports. Rule 2 gives a positive signal from closed ports and silence from open ones, which inverts the logic. Everything below is one of the two.

TCP connect scan

What it sends. The full handshake: SYN, then on receiving SYN/ACK, the final ACK, establishing the connection, which is then closed.

How it decides. The connection either succeeds (open) or is refused with RST (closed).

Why it is used. It requires no special privileges, because it asks the operating system to make an ordinary connection rather than constructing raw packets. On a machine where the tester lacks administrative rights, it may be the only option.

Its cost, and this is the point. The connection completes, so the application on the target accepts it and typically logs it: a web server records a request, an SSH daemon records a connection, a mail server may log a session. It is the noisiest TCP scan at the application level, and it leaves the clearest evidence.

Reliability. Excellent. It uses the normal path, so its results are unambiguous.

TCP SYN scan (half-open)

What it sends. A SYN. On receiving SYN/ACK it sends RST rather than the final ACK, tearing the connection down before it is established.

How it decides. SYN/ACK means open, RST means closed, silence means filtered.

Why it is the default. It is fast, it is reliable because it uses rule 1's mandated responses, and the connection never reaches the application, so the service usually does not log it.

munotes.in181

The Scan Types: Connect, SYN, FIN, NULL and XMAS

Where the "stealth" claim is true and where it is not. True: the application layer commonly records nothing, because no connection was established. Not true: the network sees a burst of SYNs from one source across many ports with no completing ACKs, which is the most recognisable pattern in intrusion detection. Calling it a stealth scan is a statement about application logs only, and the next-but-one chapter develops this.

Its cost to the target. Each probe to an open port leaves a half-open entry in the backlog until it times out, so a wide SYN scan consumes resources on the target even though nothing malicious was intended.

Privilege. It constructs raw packets, so it normally requires administrative rights on the scanning machine.

FIN, NULL and XMAS: the inverse scans

These three share one idea and differ only in which flags they set. All rely on rule 2.

What each sends:

ScanFlags set
FINFIN alone
NULLnone at all
XMASFIN, PSH and URG together

The XMAS name comes from the packet being "lit up" with several flags, like a Christmas tree. There is no deeper logic: the three combinations are all equally meaningless to a listening service, which is the whole point.

How they decide. By rule 2, a closed port replies RST; an open port sends nothing. So:

  • RST received means closed.
  • No response means open or filtered, and the scan cannot distinguish them.

Note the inversion carefully, because it is the commonest confusion in the topic: with a SYN scan, silence means filtered and is uninformative; with these scans, silence is the positive result for an open port. The scanner learns about open ports from what does not arrive.

Why anyone uses them. Two reasons, both historical and both weaker now. They avoid sending SYNs, so a simple filter or logging rule that watches for SYNs to closed ports may not record them. And some stateless packet filters permitted through packets that were not SYNs, on the assumption they belonged to established connections, so these scans could pass where a SYN scan was blocked. Modern stateful firewalls track connections and drop segments belonging to none, which defeats all three.

Their fatal weakness, and it is examinable. Rule 2 is not universally implemented. Several widely used operating systems, notably the Windows family, reply RST to everything, whether the port is open or closed. Against such a host these scans report every port closed, which is confidently and completely wrong. A scanner cannot know in advance whether the target follows the rule.

Therefore: the result "open or filtered" is genuinely ambiguous, and a result of "all ports closed" from one of these scans should be treated as evidence about the target's TCP implementation rather than about its ports. They are less reliable than a SYN scan, not more clever.

munotes.in182

The Scan Types: Connect, SYN, FIN, NULL and XMAS

Comparing them

ConnectSYNFIN / NULL / XMAS
Rule used112
Completes handshakeYesNoNo
Open port signalConnection succeedsSYN/ACKSilence
Closed port signalRSTRSTRST
Filtered distinguishableYesYesNo (open or filtered)
Application logs itUsually yesUsually noUsually no
Network sensor sees itYesYes, characteristicallyYes, and more easily (abnormal packets)
Needs raw packetsNoYesYes
ReliabilityHighHighLow: fails against hosts that always RST

The professional summary: use a SYN scan unless you cannot, in which case use connect; the inverse scans are a specialist option whose results require corroboration.

What the defender sees

The half that matters, and the reason these scans are not clever.

A connect scan appears in application logs as many short connections from one source, often to many ports, most refused. It is trivially visible to anyone reading logs.

A SYN scan appears at the network as many SYNs from one source, spread across ports, with no completing ACKs and often RSTs from the scanner. Intrusion detection systems are specifically tuned for exactly this, and it is among the most reliably detected activities on a network.

FIN, NULL and XMAS scans are, if anything, easier to detect than a SYN scan, and students frequently believe the opposite. A bare FIN for no connection, or a packet with no flags set at all, does not occur in legitimate traffic. A NULL packet is invalid by construction. So a sensor watching for anomalous flag combinations catches them immediately, and their rarity means almost no false positives. Their only advantage was against simple filters that no longer predominate.

The general lesson for the block: evasion at one layer is visibility at another. Avoiding the application log means constructing unusual packets, and unusual packets are exactly what network sensors are designed to notice.

A worked example

A tester, with authorisation, scans a single host three ways and compares.

SYN scan of the common ports: 22 and 443 return SYN/ACK (open); 25 and 110 return RST (closed); 3306 and 8080 return nothing (filtered). A clear, three-state picture.

Connect scan of the same ports: the same results, and afterwards the host's logs show connection entries for 22 and 443 from the tester's address, which the SYN scan did not produce.

XMAS scan of the same ports: 25 and 110 return RST (closed, agreeing); 22, 443, 3306 and 8080 return nothing, reported as open or filtered. Compared with the SYN results, the XMAS scan has merged the genuinely open ports with the filtered ones and lost the distinction, while adding nothing. Had the target been a Windows host, the same scan would have returned RST for all six and reported everything closed.

munotes.in183

The Scan Types: Connect, SYN, FIN, NULL and XMAS

The conclusion for the report is methodological: the SYN scan gave the usable result, the connect scan gave the same information at the cost of appearing in application logs, and the XMAS scan gave a strictly less informative answer. The tester also checks the client's monitoring and finds that all three were detected, which is recorded as a positive finding about the client's intrusion detection.

What beginners get wrong

  • Thinking a SYN scan is invisible. It avoids application logs, not network sensors, which are tuned for exactly its pattern.
  • Believing FIN, NULL and XMAS are stealthier. They send packets that never occur legitimately, so anomaly detection catches them more easily, not less.
  • Trusting "all ports closed" from an inverse scan. Hosts that reply RST regardless of state, including Windows, produce exactly that result. It is information about the stack, not the ports.
  • Reading silence the same way in every scan. With SYN scanning silence means filtered; with the inverse scans silence is the positive indication of an open port.
  • Forgetting that a connect scan needs no privileges. That is its reason for existing.
  • Thinking a scan is harmless to the target. A SYN scan leaves half-open entries consuming backlog until they expire.

Quick revision

  • Two rules: (1) SYN gets SYN/ACK from open and RST from closed; (2) a non-SYN segment for no connection gets RST from closed and is ignored by open.
  • Connect: completes the handshake; no privilege needed; reliable; logged by the application.
  • SYN (half-open): SYN then RST; the default; reliable; three states; needs raw packets; leaves half-open entries; "stealth" refers only to application logs.
  • FIN / NULL / XMAS (FIN alone / no flags / FIN+PSH+URG): use rule 2, so RST means closed and silence means open or filtered. Cannot distinguish open from filtered, and fail entirely against stacks that always reply RST, reporting everything closed.
  • Detection: connect shows in application logs; SYN shows as many SYNs without ACKs, the classic sensor signature; the inverse scans send packets that never occur legitimately and are easier to flag.
  • Principle: evasion at one layer is visibility at another.

Test yourself

  1. State the two specification rules from which all TCP scan types are derived.

First, a SYN sent to an open port must be answered with SYN/ACK and to a closed port with RST. Second, a segment that is not a SYN and belongs to no existing connection must be answered with RST by a closed port and ignored by an open one.

munotes.in184

The Scan Types: Connect, SYN, FIN, NULL and XMAS

  1. Why is a SYN scan preferred over a connect scan, and what is the sole sense in which it is "stealthy"?

It is faster and does not complete the handshake, so the connection never reaches the application and the service usually does not log it. That is the only sense in which it is stealthy: at the network level a burst of SYNs without completing ACKs is the signature intrusion detection is most tuned to catch.

  1. How do FIN, NULL and XMAS scans decide a port is open, and why is the result ambiguous?

They rely on the rule that an open port ignores a segment belonging to no connection while a closed port replies RST, so receiving RST means closed and receiving nothing suggests open. The result is ambiguous because a firewall dropping the packet also produces silence, so open and filtered cannot be distinguished.

  1. Why can an inverse scan report every port closed on a host that has open ports?

Because the rule it depends on is not implemented uniformly: some operating systems, including the Windows family, reply RST to such segments regardless of whether the port is open. Against those hosts every probe returns RST and the scan concludes, wrongly and confidently, that all ports are closed.

  1. Why are FIN, NULL and XMAS scans easier for a network sensor to detect than a SYN scan?

Because they send flag combinations that do not occur in legitimate traffic: a bare FIN for a non-existent connection, or a segment with no flags set at all, which is invalid by construction. Their rarity makes them a high-confidence, low-false-positive signal for anomaly detection, whereas SYNs are ordinary packets distinguished only by their pattern.

Contents This chapter on its own page

munotes.in185

Chapter Thirty-Nine

ACK Scanning and UDP Scanning

Syllabus topic Module 1, "Network Scanning and Port Scanning Techniques: ... ACK scans"

In one line

An ACK scan does not find open ports at all; it maps which ports a firewall is filtering. A UDP scan looks at the other transport protocol, where silence is ambiguous, results are slow, and some of the most valuable services live.

In examination wording: an ACK scan sends segments with only the ACK flag set to determine whether a stateless filter permits them, classifying ports as unfiltered or filtered rather than open or closed; UDP scanning sends datagrams to UDP ports and infers state from an ICMP port-unreachable message indicating closed, a service response indicating open, or silence, which is ambiguous.

The ACK scan

What it sends and why

A segment with only the ACK flag set. In normal traffic an ACK acknowledges data within an established connection, so a bare ACK arriving out of nowhere belongs to no connection.

By rule 2 from the previous chapter, any host receiving a segment for a connection it does not have replies RST, and crucially it does this whether the port is open or closed. An open port and a closed port respond identically.

That sounds useless, and it is the point: because the host's answer carries no information about the port, anything interesting in the result must have been added by something in between.

How it decides

What comes backConclusion
RSTThe packet reached the host: the port is unfiltered
Nothing, or an ICMP administratively-prohibited messageThe packet was stopped: the port is filtered

So the states an ACK scan reports are unfiltered and filtered, never open and closed. It is a firewall-mapping tool.

What it is actually for

Discovering the firewall's rule set. Scanning a range of ports and recording which return RST and which are silent draws the boundary of what the filter permits. A defender can run the same scan against their own perimeter to confirm the firewall filters exactly the ports intended, which is an audit rather than an attack.

Distinguishing a stateful firewall from a stateless one. This is the technically interesting use. A stateless filter judges each packet alone, and since a bare ACK looks like part of an established conversation, many stateless rule sets let it through, so the scan gets RSTs. A stateful firewall tracks connections, knows this ACK belongs to none, and drops it, so the scan gets silence. Comparing an ACK scan with a SYN scan therefore reveals the kind of firewall in place:

SYN scan resultACK scan resultInference
FilteredUnfiltered (RST)A stateless filter blocking SYNs but passing ACKs
FilteredFiltered (silence)A stateful firewall
Open or closedUnfilteredNo filtering on that port

Host discovery, as the earlier chapter noted: an RST proves the host is alive, and an ACK probe passes some filters that block SYNs.

munotes.in186

ACK Scanning and UDP Scanning

Its limits

It says nothing about whether a service is running, so it is never used alone. It is a complement to a SYN scan, and its output is a map of the filter, not of the services. A tester who reports "the ACK scan found no open ports" has misunderstood the tool.

UDP scanning

Why it is hard

UDP has no handshake, so the clean two-way signal of TCP does not exist. What a scanner can rely on is thinner:

  • A closed UDP port should generate an ICMP port-unreachable message. That is the one reliable negative signal.
  • An open UDP port typically sends nothing at all, unless the datagram happened to be a valid request for that service, in which case a service-specific reply comes back.
  • A filtered port also sends nothing.

So the common case is that open and filtered look identical, and the state is reported as open or filtered. This is the same ambiguity as the inverse TCP scans, and here it is unavoidable rather than a side effect.

Why it is slow

Two reasons, and both matter practically.

ICMP rate limiting. Operating systems limit how many ICMP error messages they generate per second, commonly to a small number. A scanner probing many closed ports receives those replies at a throttled rate and must wait, so a full UDP scan of 65,535 ports against a single host can take hours where the TCP equivalent takes seconds.

Retransmission. Because UDP is unreliable and silence is meaningful, a scanner must send each probe several times before concluding that silence is real, multiplying the work.

The practical consequence, and the honest advice: a full UDP scan is rarely worth the time, so testers scan a targeted list of the UDP ports that matter and document that they did so, rather than claiming full coverage.

Making it informative: protocol-specific probes

A generic empty datagram sent to an open UDP port usually elicits nothing, because the service does not recognise it as a request. A protocol-specific probe does much better: send something that looks like a real DNS query to port 53, a real SNMP request to 161, a real NTP request to 123, and an open service answers, converting "open or filtered" into a definite open with the service identified at the same time.

This is why UDP scanning and service detection are effectively the same operation, in a way TCP scanning and service detection are not.

The UDP services that matter

UDP is where several of the most productive findings live, which is the argument against skipping it:

munotes.in187

ACK Scanning and UDP Scanning

PortServiceWhy it matters
53DNSZone transfers, cache poisoning, open resolvers used for amplification
67, 68DHCPNetwork configuration; rogue servers
69TFTPNo authentication at all; often holds device configurations
123NTPAmplification; time manipulation affects certificate and log validity
161, 162SNMPDefault community strings, one of the most common real findings
500IKEVPN negotiation; reveals the VPN's presence and configuration
1900SSDPDevice discovery; amplification
5353mDNSLocal service discovery; leaks host and service names

Three of these (DNS, NTP, SSDP) are the classic amplification reflectors for the denial-of-service chapter, and one (SNMP) is the subject of its own enumeration chapter. An assessment that scans only TCP misses all of them.

The defensive reading

Against ACK scanning. A stateful firewall defeats it, because it drops segments belonging to no tracked connection. That is the recommendation, and it is the same recommendation as for the inverse TCP scans, which is convenient: one control addresses several techniques. Beyond that, a firewall that drops rather than rejects yields silence rather than an informative ICMP message.

Against UDP scanning. Filter UDP as deliberately as TCP, which is frequently not done: rule sets are often written carefully for TCP and left permissive for UDP. Close or restrict the services that need not be public, put SNMP on a management network with non-default community strings and version 3, disable TFTP, and ensure DNS resolvers are not open to the internet, since an open resolver becomes an amplifier used against third parties. Rate limit ICMP error generation, which slows scanning as a side effect of a setting that is sensible anyway.

Detection. UDP scanning is detectable by the same logic as TCP: many datagrams to many ports from one source, and a burst of outgoing ICMP port-unreachable messages, which is a distinctive signal that a host is being swept.

A worked example

A tester assesses a perimeter and combines the scans.

SYN scan: ports 80 and 443 open; 22 filtered; 3306 filtered; everything else filtered.

ACK scan of the same ports: 80 and 443 return RST (unfiltered, as expected); 22 returns nothing; 3306 returns nothing. So the firewall is stateful, dropping rather than rejecting, and it is filtering 22 and 3306 rather than those services being absent. The tester now knows the firewall's behaviour and that something may well be listening behind the filtered ports.

UDP scan of a targeted list: 53 responds to a protocol-specific DNS query (open); 161 responds to an SNMP request (open); 123 responds (open); the rest are silent or report closed.

The findings from the UDP half turn out to be the report's most serious:

munotes.in188

ACK Scanning and UDP Scanning

  • SNMP (161) is reachable from the internet. The enumeration chapter will show what that yields if the community string is a default, and it should not be internet-facing at all.
  • DNS (53) answers a recursive query from an arbitrary source, making it an open resolver usable for amplification attacks against others. That is a finding about harm to third parties as well as to the client.
  • NTP (123) is reachable and should be checked for the same amplification role.

Had the tester scanned only TCP, the report would have recorded a well-configured perimeter with two open web ports. The lesson is in that contrast.

What beginners get wrong

  • Expecting an ACK scan to find open ports. It cannot; it reports unfiltered against filtered, and that is its purpose.
  • Missing what the SYN and ACK comparison reveals. Filtered under SYN but unfiltered under ACK indicates a stateless filter; filtered under both indicates a stateful firewall.
  • Skipping UDP because it is slow. Some of the most serious findings (SNMP defaults, open resolvers, TFTP) are only visible there.
  • Attempting a full 65,535-port UDP scan routinely. Rate limiting makes it take hours; scan a targeted list and say so in the report.
  • Sending empty datagrams and reporting the results confidently. Without protocol-specific probes, open services stay silent and everything reads as "open or filtered".
  • Reading UDP silence as closed. Closed has a signal, the ICMP port-unreachable. Silence means open or filtered.

Quick revision

  • ACK scan: a bare ACK; every host replies RST regardless of port state, so the host's answer is uninformative and anything interesting was added in between. RST means unfiltered, silence means filtered. It maps the firewall, never the services.
  • SYN filtered plus ACK unfiltered indicates a stateless filter; filtered under both indicates a stateful firewall. An RST also proves the host is alive.
  • UDP scan: closed gives ICMP port-unreachable; open usually gives nothing; filtered gives nothing. So the common result is open or filtered.
  • It is slow because of ICMP rate limiting and the need to retransmit; scan a targeted port list and document that.
  • Protocol-specific probes (a real DNS, SNMP or NTP request) turn silence into a definite open and identify the service at once.
  • UDP services that matter: 53 DNS, 69 TFTP, 123 NTP, 161 SNMP, 500 IKE, 1900 SSDP, 5353 mDNS. DNS, NTP and SSDP are the amplification reflectors.
  • Defences: a stateful firewall (defeats ACK scanning and the inverse scans), deliberate UDP filtering, SNMPv3 on a management network, no open resolvers, and ICMP rate limiting.

Test yourself

  1. What does an ACK scan determine, and why does the host's own response carry no information about the port?
munotes.in189

ACK Scanning and UDP Scanning

It determines whether a port is filtered or unfiltered by a firewall. The host's response carries no port information because a segment belonging to no existing connection is answered with RST whether the port is open or closed, so the reply is identical either way and any variation in the result was introduced by an intermediate device.

  1. How can comparing SYN and ACK scan results reveal the type of firewall?

If a port is filtered to a SYN scan but returns RST to an ACK scan, a stateless filter is blocking connection attempts while permitting packets that resemble established traffic. If the port is filtered under both, the firewall is stateful, tracking connections and dropping segments that belong to none.

  1. Why is UDP scanning slow and ambiguous?

Ambiguous because an open UDP port normally returns nothing, exactly as a filtered port does, so only the ICMP port-unreachable message from a closed port is a reliable signal. Slow because operating systems rate-limit ICMP error generation, throttling the responses, and because silence is meaningful the scanner must retransmit each probe several times before trusting it.

  1. How does a protocol-specific probe improve a UDP scan?

By sending something a particular service will recognise as a valid request, such as a genuine DNS query to port 53 or an SNMP request to 161, so an open service replies. This converts an ambiguous "open or filtered" into a confirmed open port and identifies the service at the same time.

  1. Give three UDP services whose exposure produces serious findings, and say why each matters.

SNMP on 161, because default community strings expose a device's full management information; DNS on 53, because a resolver open to the internet can be abused as an amplifier in denial-of-service attacks against third parties, and because it may permit zone transfers; and TFTP on 69, because it offers no authentication at all and frequently holds device configuration files. NTP on 123 is also acceptable, as an amplification reflector and because manipulating time affects certificate validity and log integrity.

Contents This chapter on its own page

munotes.in190

Chapter Forty

Port States, Service and Version Detection, and OS Fingerprinting

Syllabus topic Module 1, "Network Scanning and Port Scanning Techniques"

In one line

A scan's answer is a state (open, closed or filtered), and a state is not yet useful. Service detection finds what is listening, version detection finds which release, and OS fingerprinting identifies the platform, which together turn a port number into a list of known vulnerabilities.

In examination wording: port scanning classifies ports as open, closed or filtered, with combined states where the scan cannot distinguish; service detection determines the application protocol in use; version detection identifies the specific product and release through banner analysis and probe responses; operating-system fingerprinting infers the platform from characteristic differences in protocol implementation.

The port states

Three primary states, and a thorough scanner reports six.

Open. A service is listening and accepted the probe. This is a target, and it is what the scan is looking for.

Closed. The host is reachable and answered, but nothing is listening on that port. This is not a failure: it proves the host exists, it shows the firewall is not filtering that port, and a port that is closed today may be opened tomorrow, so an inventory of closed ports has value.

Filtered. No useful reply arrived, because something dropped the probe. The state of the service is unknown. Filtered is information about the firewall, not about the application.

The three combined states:

Open or filtered. The scan could not distinguish, because the technique's positive signal is silence. Produced by UDP scans and by the FIN, NULL and XMAS scans.

Closed or filtered. The scan could not determine whether the host or a filter answered; produced by some specialised techniques.

Unfiltered. Reachable, but the technique cannot say whether a service is listening. Produced by the ACK scan.

The distinction students must hold: closed is an answer, filtered is the absence of one. Reporting a filtered port as closed asserts that nothing is listening when the truth is that nobody knows, and that is a material error in a report.

Service detection

An open port is an invitation to guess. Port 443 is probably HTTPS, port 22 probably SSH. But the assignment of services to port numbers is convention, not enforcement: a web server can run on 8080 or 7777, a database can be moved to an unusual port, and an attacker's backdoor certainly will not use a standard one.

Service detection replaces the guess with evidence. The scanner connects and interacts, sending a probe and comparing the response against known behaviour. Many services announce themselves on connection with a banner; those that do not can still be identified because their reply to a particular request is distinctive.

The output is the application protocol actually in use, which may contradict the port number. Finding SSH on 443, or an unrecognised service on 8080, is itself a finding: the first may be a deliberate attempt to traverse a restrictive firewall, the second warrants investigation.

munotes.in191

Port States, Service and Version Detection, and OS Fingerprinting

Version detection

The step that matters most, because this is what makes the CVE databases usable.

What it does. Determines the product and release: not merely "a web server" but "this server software, version 2.4.x", and often the operating-system distribution and the modules or libraries loaded.

How it works. Partly from banners, which frequently include a version string, and partly from behavioural differences: how the service responds to unusual or malformed requests, which options it supports, the exact wording of its errors. Different releases differ in small ways that a probe database records, so a version can often be determined even where the banner has been suppressed or altered.

Why it is the pivot of the whole assessment, and this is the examinable connection:

Open port, then service, then version, then look the version up against CVE and the National Vulnerability Database, then obtain a list of known vulnerabilities with severities, then prioritise.

Every step before version detection narrows the target; the version is what converts reconnaissance into an actionable list. That is why the enumeration chapters that follow spend their effort on getting versions accurately, and why the hardening chapters treat version disclosure as worth reducing even though it is not a defence in itself.

The characteristic errors, which a careful assessor accounts for:

  • Back-ported fixes. Long-term-support distributions frequently apply security patches without changing the version string, so a server reporting an old version may be fully patched. Matching versions to CVEs therefore produces false positives, and a finding based on a banner alone is a hypothesis to confirm, not a conclusion.
  • Suppressed or falsified banners. Some administrators remove or alter version strings, producing false negatives or misdirection. Behavioural detection often defeats this, which is why banner suppression is a weak control.
  • Load balancers and proxies. The banner may describe the intermediary rather than the server behind it.

Operating-system fingerprinting

What it is. Inferring the target's operating system and version from how its network stack behaves, because the standards leave many details to the implementer and different systems make different choices.

What it reads. The default TTL in IP headers, the initial TCP window size, which TCP options are offered and in what order, how sequence numbers are generated, and, most informatively, how the stack handles unusual or malformed packets, where the standard is silent and implementations diverge most. The combination of these values forms a signature matched against a database.

Two approaches:

Active fingerprinting sends deliberately crafted probes designed to provoke differences. It is accurate and it is noisy, because the packets are abnormal and therefore conspicuous to a sensor, exactly as with the inverse scans.

munotes.in192

Port States, Service and Version Detection, and OS Fingerprinting

Passive fingerprinting examines traffic the target sends anyway, without sending anything. It is undetectable and less precise, and it is available to a defender monitoring their own network, which is a legitimate use: passively fingerprinting your own traffic reveals devices that are not in the inventory.

Why it matters to an assessment. Vulnerabilities are platform-specific, so the operating system narrows which CVEs apply and which techniques are relevant. It also reveals unexpected devices: a signature indicating an embedded platform among a range of ordinary servers usually means a printer, a camera or an appliance, and those are frequently unmanaged, unpatched and forgotten, which connects back to the inventory argument of the footprinting block.

Its limits. Network devices, load balancers and virtualisation can alter the characteristics; firewalls that normalise traffic deliberately defeat it; and a single unusual result should not be over-read.

Putting the pipeline together

The complete sequence, which is what a vulnerability assessment actually is:

StepProducesChapter
Host discoveryLive addressesearlier
Port scanningPort statesearlier
Service detectionThe application protocolthis
Version detectionProduct and releasethis
OS fingerprintingThe platformthis
Vulnerability lookupCVEs with CVSS severitiesthe vulnerability block
PrioritisationAn ordered list of workthe CVSS chapters

A scanner performs all of it automatically, which is why a vulnerability scanner's report looks the way it does, and why understanding this pipeline explains both its value and its failure modes: it cannot find flaws in software it failed to identify, and it inherits every error in version detection.

A worked example

A tester scans one host with authorisation and works the pipeline.

States: 22, 443 and 8080 open; 25 closed; 3306 filtered.

Service detection: 22 is SSH as expected; 443 is HTTPS; 8080 is not a web server but a Java application server management interface, which the port number alone would not have revealed.

Version detection: SSH reports a current release; the web server reports a version; the application server reports its product and release, and it is three major versions behind.

OS fingerprinting: the stack signature indicates a Linux distribution, consistent with the service banners.

Vulnerability lookup: the application server's version has several published vulnerabilities, one Critical and remotely exploitable without authentication.

The findings, in order:

  1. An outdated application server management interface is exposed on 8080, with a Critical known vulnerability. Urgent: patch, and remove the interface from internet exposure entirely, since a management interface should never face the public.
  2. Port 3306 is filtered, so a database may be present behind the firewall. Recorded as unknown, not as absent, and worth confirming from inside.
  3. The web server's version is disclosed in its banner. A minor hardening note, with the observation that patching, not suppression, is the real control.
munotes.in193

Port States, Service and Version Detection, and OS Fingerprinting

Note that the most serious finding came from the port whose service the number would have mislabelled. That is the argument for doing service detection rather than assuming.

What beginners get wrong

  • Treating filtered as closed. Closed is an answer meaning nothing is listening; filtered is the absence of an answer, so the service state is unknown. Reporting one as the other is a material error.
  • Assuming the port number identifies the service. It is a convention; detection is evidence. Services on unexpected ports are themselves findings.
  • Trusting a banner absolutely. Back-ported patches leave old version strings (false positives) and banners can be suppressed or falsified (false negatives). Confirm before reporting.
  • Thinking banner suppression protects the host. Behavioural version detection frequently defeats it; patching is the control.
  • Ignoring closed ports entirely. They prove the host is alive and show what the firewall is not filtering.
  • Over-reading a fingerprint. Intermediaries and virtualisation distort the signature; corroborate with service evidence.

Quick revision

  • States: open (a service is listening), closed (host alive, nothing listening, still informative), filtered (dropped, state unknown), plus open or filtered (UDP and inverse scans), closed or filtered, and unfiltered (ACK scan).
  • Service detection identifies the application protocol by probing, because port numbers are convention; a service on an unexpected port is a finding.
  • Version detection identifies product and release from banners and behavioural differences. It is the pivot: version, then CVE, then severity, then priority.
  • Errors: back-ported fixes cause false positives, suppressed banners cause false negatives, intermediaries mislead.
  • OS fingerprinting reads TTL, window size, TCP options and handling of malformed packets. Active is accurate and noisy; passive is silent, less precise, and useful defensively for finding unmanaged devices.
  • The pipeline: discovery, port state, service, version, platform, CVE lookup, prioritisation.

Test yourself

  1. Distinguish closed from filtered, and say why confusing them matters in a report.

Closed means the host answered and nothing is listening on that port; filtered means no usable reply arrived because an intermediate device dropped the probe, so the service's state is unknown. Reporting a filtered port as closed asserts that no service exists when in fact nothing is known, which can conceal an exposed service behind a partially permissive filter.

  1. Why is version detection described as the pivot of a vulnerability assessment?

Because CVE records identify flaws in specific products at specific versions, so only once the product and release are known can the findings be looked up against vulnerability databases to yield known vulnerabilities with severities. Every earlier step narrows the target; the version is what makes the result actionable.

munotes.in194

Port States, Service and Version Detection, and OS Fingerprinting

  1. Why can a correct version string still produce a false positive, and a suppressed one still be defeated?

A false positive arises because long-term-support distributions back-port security fixes without changing the version string, so an apparently old version may be fully patched. A suppressed banner can still be defeated because version detection also uses behavioural differences, such as responses to unusual requests and supported options, which differ between releases.

  1. What characteristics does OS fingerprinting read, and what is the difference between the active and passive forms?

It reads default TTL values, initial TCP window size, which TCP options are offered and in what order, sequence-number generation, and especially how the stack handles malformed or unusual packets where the standard is silent. Active fingerprinting sends crafted probes and is accurate but conspicuous; passive fingerprinting only observes traffic the target already sends, so it is undetectable but less precise, and it is useful to defenders for spotting unmanaged devices.

  1. Why is finding a service on a non-standard port significant?

Because port assignments are conventions rather than rules, so a service running where it is not expected may indicate a deliberate attempt to traverse restrictive filtering, a management interface that should not be exposed, or an unauthorised service. It also means an assessment that assumed the service from the port number would have mislabelled it and possibly missed the most serious finding.

Contents This chapter on its own page

munotes.in195

Chapter Forty-One

Firewall and Filter Detection

Syllabus topic Module 1, "Network Scanning and Port Scanning Techniques: ... along with firewall detection logic"

In one line

A firewall cannot hide completely: the way it interferes with replies tells you it is there and roughly what it is doing. A firewall that rejects announces itself; one that drops makes the scanner guess, which is why dropping is the better default.

In examination wording: firewall detection is the inference, from the pattern of responses and non-responses to crafted probes, of whether traffic is being filtered, by what kind of device, and according to what rules; a filtering device that returns an explicit refusal discloses its presence and rule, whereas one that silently discards traffic denies the scanner the information it seeks.

The logic in one idea

The handshake chapter established that a direct TCP exchange has only two lawful outcomes: SYN/ACK or RST. Silence is impossible between two hosts talking directly.

Therefore any third outcome is evidence of a third party. That is the whole of firewall detection logic, and everything below refines it: which third outcome, on which ports, with what timing, tells you what kind of device is in the path and what rule it is applying.

Reject against drop

A filtering device meeting unwanted traffic has two choices, and the difference governs everything.

Reject. Send back an explicit refusal: a TCP RST, or an ICMP destination unreachable message, often with the code meaning administratively prohibited. The sender learns immediately that the connection will not happen.

Drop. Discard the packet and send nothing. The sender waits, retransmits, and eventually times out.

RejectDrop
Scanner learnsA filter exists, and this port is blockedOnly that no answer came
Reported stateFiltered, with the firewall confirmedFiltered, cause unproven
Speed of failureImmediateA full timeout, then retries
Effect on scan timeFastSlow, which is itself a defence
Legitimate misrouted trafficFails fast and clearlyHangs, which frustrates diagnosis

The security conclusion: drop is the better default for internet-facing filters, because it gives an attacker less information and makes scanning expensive in time. The ICMP administratively prohibited message is a particularly generous disclosure, since it names the cause, and it should not be sent to untrusted networks.

The counter-argument deserves a fair hearing: dropping makes legitimate misconfiguration hard to diagnose, because a client with a wrong setting hangs instead of failing cleanly. The usual resolution is to drop at the perimeter and reject internally, so outsiders learn nothing while staff get useful errors.

What each observation lets you infer

This is the "logic" MU asks for, set out as inferences rather than tools.

RST from every port, open and closed alike. No filtering on those ports, or a device that rejects uniformly. Compare with an ACK scan to distinguish.

munotes.in196

Firewall and Filter Detection

Some ports answer, others are silent. A firewall with per-port rules. The boundary between answering and silent ports is the rule set, and mapping it is the single most useful output of this work.

Every port silent, but the host is known to be alive (from an ARP reply or another route): a default-deny firewall dropping everything not explicitly permitted. This is the secure posture, and the fact that it is recognisable is not a weakness.

Silence on a SYN scan but RST on an ACK scan. A stateless filter: it blocks connection attempts but passes segments that resemble established traffic. This is the comparison developed in the ACK-scan chapter and it is the most technically informative single observation in the block.

Silence on both. A stateful firewall tracking connections.

ICMP administratively prohibited. A rejecting filter, and the message frequently reveals the filtering device's own address, which is a further disclosure.

Timing differences. A dropped packet times out; a rejected one fails at once. Consistent slow failures across a range indicate dropping.

Different results by source port or protocol. Some rule sets permit traffic that appears to come from a trusted service port, or treat UDP differently from TCP. Testing from varied source ports can reveal a rule written more loosely than intended, which is a genuine finding.

Hop-count differences. A traceroute that stops at a consistent hop before the target locates the filtering device in the path and reveals the perimeter's structure.

The kinds of firewall

The inference depends on what is in the path, so the vocabulary is needed.

Packet filter (stateless). Judges each packet alone against rules on addresses, ports and flags. Fast, simple, and unable to tell whether a packet belongs to a real conversation, which is why bare ACK probes pass it.

Stateful inspection firewall. Maintains a table of active connections and permits only packets that fit one, or that legitimately start one. Defeats the ACK scan and the inverse TCP scans in one stroke, and is the modern baseline.

Application-layer firewall or proxy. Understands the protocol it is carrying and can inspect content, not just headers. A web application firewall is this kind specialised for HTTP, and it reappears in the SQL injection and cross-site scripting chapters as an outer net.

Next-generation firewall. Stateful inspection combined with application awareness, identity, and intrusion prevention in one device.

Host-based firewall. On the machine itself. Its importance for this book is that it makes a host unreachable without being absent, which is why the host-discovery chapter insisted that silence is not absence and why ARP finds hosts nothing else does.

Turning the logic into a configuration

Everything above, read as instructions:

  • Default deny. Permit what is needed and drop the rest, rather than blocking known-bad and permitting the rest.
  • Drop, do not reject, at the perimeter. Deny scanners the confirmation and make scanning slow. Reject internally, where diagnosis matters more than obscurity.
  • Do not send administratively-prohibited messages to untrusted networks, since they name the cause and often the device.
  • Be stateful. One change defeats ACK scanning and the FIN, NULL and XMAS scans together.
  • Filter UDP as deliberately as TCP. Rule sets are routinely careful for TCP and permissive for UDP, and the previous chapter showed what lives there.
  • Do not trust source ports. A rule permitting traffic that claims to come from a trusted service port is trivially satisfied by an attacker who chooses that source port.
  • Filter egress as well as ingress. Controlling what may leave breaks command-and-control and data exfiltration, and the Log4Shell case showed it can break an exploit chain outright. It is the most commonly omitted control on this list.
  • Match IPv6 to IPv4. A carefully filtered IPv4 perimeter with an unfiltered IPv6 path is a recurring real finding.
  • Audit the rules against intent, with an ACK scan from outside, and remove rules nobody can justify. Rule sets accumulate.
munotes.in197

Firewall and Filter Detection

A worked example

An assessor audits a perimeter, with authorisation, and reasons from observations to conclusions.

ObservationInference
SYN scan: 80 and 443 answer SYN/ACK; all other ports silent; no port returns RSTDefault-deny firewall that drops. The secure posture, and the absence of any closed port is the tell
ACK scan: only 80 and 443 return RST; the rest silentStateful, since a stateless filter would have passed the bare ACKs
No ICMP administratively-prohibited messages anywhereCorrectly configured not to disclose the cause
Traceroute stops two hops before the hostThe filtering device sits there; the perimeter's structure is visible
Repeating the SYN scan with source port 53Port 3306 now answers. A rule permits traffic claiming to come from DNS
IPv6 scan of the same service names22 and 3306 open over IPv6 with no equivalent filtering

The first four findings are positive and should be reported as such. The last two are serious:

  1. A source-port rule permits access to the database port. Anyone choosing source port 53 reaches it. Remove the rule or make it stateful and address-restricted.
  2. The IPv6 path is unfiltered. The carefully built IPv4 posture is bypassed entirely by using IPv6, which is the more serious of the two because it exposes SSH as well.

The example makes the chapter's point: the firewall was well configured in the ways people usually check, and the failures were in the two places people usually do not, a permissive source-port rule and an unmatched IPv6 policy.

munotes.in198

Firewall and Filter Detection

What beginners get wrong

  • Thinking a firewall makes a host invisible. It changes what the scan learns; open ports you publish are still found, and silence itself is a signal.
  • Assuming reject is friendlier and therefore better. It is friendlier to misrouted legitimate traffic and gives an attacker a clear map. Drop at the perimeter.
  • Reading filtered as closed. Filtered means a device intervened and the service state is unknown.
  • Using an ACK scan to find services. It maps filtered against unfiltered; use SYN for services.
  • Forgetting egress filtering. Controlling outbound traffic breaks command-and-control and exfiltration and can defeat an exploit that needs to fetch a payload.
  • Auditing IPv4 only. An unfiltered IPv6 path silently bypasses the whole rule set.
  • Trusting source ports. Any attacker can choose a source port; a rule based on one is not a control.

Quick revision

  • The logic: a direct TCP exchange must yield SYN/ACK or RST, so any other outcome proves a third party is in the path.
  • Reject (RST or ICMP administratively prohibited) confirms a filter and fails fast; drop yields silence and slow timeouts. Drop at the perimeter, reject internally.
  • Inferences: mixed answering and silent ports mean per-port rules; all silent with the host known alive means default deny; silent to SYN but RST to ACK means stateless; silent to both means stateful; timing and hop counts locate the device; varying the source port can expose a loose rule.
  • Kinds: packet filter (stateless), stateful inspection (the baseline, defeats ACK and inverse scans), application-layer or proxy (including web application firewalls), next-generation, and host-based (makes a host unreachable without being absent).
  • Configuration: default deny, drop at the perimeter, no prohibited messages outward, stateful, deliberate UDP rules, no source-port trust, egress filtering, IPv6 matching IPv4, and periodic rule audits against intent.

Test yourself

  1. State the single principle on which firewall detection rests.

That a direct TCP exchange between two hosts can only produce SYN/ACK or RST, so any other outcome, especially silence or an ICMP error, is evidence that a third device intervened. What kind of outcome, on which ports, with what timing, then indicates the type of device and its rules.

  1. Compare reject and drop, and say which belongs at an internet-facing perimeter and why.

Reject returns an explicit refusal (RST or ICMP administratively prohibited), confirming a filter and failing immediately; drop discards silently, producing timeouts. Drop belongs at the perimeter because it denies the scanner confirmation and makes scanning slow, whereas reject is preferable internally where fast, clear diagnosis of misconfiguration matters more than withholding information.

  1. A host returns SYN/ACK on two ports and silence on every other port, with no port ever returning RST. What do you conclude?
munotes.in199

Firewall and Filter Detection

That a default-deny firewall is dropping all traffic other than the two permitted services. The absence of any closed port is the decisive observation, since a directly reachable host would return RST on ports with no listener.

  1. How is a stateless filter distinguished from a stateful firewall by scanning?

By comparing a SYN scan with an ACK scan. If ports are filtered to SYN but return RST to a bare ACK, the filter is judging packets individually and letting through segments that resemble established traffic, so it is stateless. If both scans are filtered, the device is tracking connections and dropping segments belonging to none, so it is stateful.

  1. Name two commonly omitted firewall controls and explain the risk of each.

Egress filtering, whose absence permits command-and-control traffic and data exfiltration and allows exploits that must fetch a remote payload to complete; and IPv6 rules matching IPv4, whose absence leaves an unfiltered parallel path that bypasses the entire carefully built IPv4 policy. A third acceptable answer is source-port trust, since an attacker can freely choose a source port, so a rule permitting traffic claiming to come from a trusted service port is not a control at all.

Contents This chapter on its own page

munotes.in200

Chapter Forty-Two

How the Scan Is Seen: Intrusion Detection and the Defender's View

Syllabus topic Module 1, "Network Scanning and Port Scanning Techniques: ... along with firewall detection logic"; Course Outcome 5

In one line

Every scan leaves a trace. A firewall decides what gets through; an intrusion detection system decides what gets noticed, and the pattern of a port scan is among the most recognisable things on a network.

In examination wording: an intrusion detection system monitors network traffic or host activity for evidence of malicious behaviour and raises alerts; an intrusion prevention system additionally blocks the traffic it identifies; detection may be signature-based, matching known patterns, or anomaly-based, identifying deviation from an established baseline, and its practical value depends on tuning to control false positives.

The claim to be justified

The scan-types chapter asserted repeatedly that "stealth" scans are stealthy only against application logs. Here is the argument.

A port scan has a shape that ordinary traffic does not:

  • One source contacting many destination ports in a short time. Legitimate clients connect to one or two ports on a server they intend to use.
  • Connections that do not complete. A SYN scan sends SYN, receives SYN/ACK, and sends RST instead of ACK. Real clients complete and then exchange data.
  • Ports contacted in order, or in a recognisable pseudo-random spread across the whole range, including ports no real client would try.
  • A high ratio of failures to successes. Most probes hit closed or filtered ports, so the source accumulates refusals at a rate no legitimate client does.
  • No application-layer activity. Where a connection does complete, nothing sensible follows.

None of these depends on the flags used, which is why the "stealth" of a half-open scan does not help: it avoids the application log and produces the same network shape. And the inverse scans are worse, because a bare FIN or a packet with no flags at all does not occur in legitimate traffic, so a sensor can flag it on the single packet without needing a pattern.

The general principle, worth stating because it recurs: evasion at one layer produces visibility at another. Avoiding the application means crafting packets, and crafted packets are conspicuous.

Where the evidence lives

A defender has several independent records, and the strength of detection comes from combining them.

Firewall logs. Denied connection attempts, with source, destination and port. A single source generating many denials across many ports is the clearest signal there is, and it requires no special equipment.

Network sensors. A device watching traffic, either inline or on a mirrored copy, applying rules and thresholds. This is where the scan shape is recognised.

Application logs. Where a connection completed. A connect scan appears here; a SYN scan usually does not.

Host logs and endpoint agents. Connection attempts recorded by the host or its own firewall, which is particularly valuable for detecting internal scanning.

munotes.in201

How the Scan Is Seen: Intrusion Detection and the Defender's View

Flow records. Summaries of who talked to whom, on what port, for how long, without capturing content. Cheap to keep in volume, and excellent for exactly this pattern: one source, many destinations, short-lived, no data transferred.

Signature against anomaly detection

The two approaches, which examiners ask to be distinguished.

Signature-based detection matches traffic against patterns of known-bad activity: a particular byte sequence, a particular flag combination, a rate of connections above a threshold.

  • Strengths: precise, explicable, and low in false positives. When it fires you know what rule matched and why.
  • Weaknesses: it can only find what someone has written a rule for. Novel activity passes, and small changes can evade a narrowly written rule.

Anomaly-based detection builds a baseline of normal behaviour and flags deviation.

  • Strengths: can catch previously unseen activity, because it does not need a description of the attack, only of normality.
  • Weaknesses: defining normal is hard, networks change, and the result is false positives, which are the practical limit of the whole field. A baseline built while an attacker was already present learns the intrusion as normal.

Real systems combine both, and add reputation (this source is known-hostile) and increasingly behavioural analytics.

For port scanning specifically, both work: signatures catch abnormal flag combinations and threshold rules catch the connection rate, while anomaly detection catches a source behaving unlike any normal client.

IDS against IPS, and where each sits

An intrusion detection system (IDS) observes and alerts. It is typically out of band, watching a copy of the traffic, so it cannot itself break anything.

An intrusion prevention system (IPS) sits inline and can drop the traffic it identifies.

The trade-off is the examinable point. An IPS stops attacks automatically, which is valuable, and it introduces two risks: a false positive now blocks legitimate traffic, potentially cutting off customers, and the device is in the path, so its failure is an outage. An IDS cannot break anything and cannot stop anything.

Common practice is to run in detection mode first, tune until confident, and then enable blocking selectively for high-confidence signatures.

By placement: network-based systems watch traffic at a chokepoint and see broadly but cannot read encrypted content without interception; host-based systems watch a single machine's activity, see what happens after decryption, and see nothing about hosts they are not installed on.

The honest limits

A student who does not understand these will over-rely on detection.

Encryption. A network sensor sees little inside a TLS session. It can still see the shape (who, when, how much, to where), which is exactly why the scanning pattern remains visible while the content does not.

The base-rate problem, the most important limit here. Consider a sensor that is 99 per cent accurate examining ten million events a day, of which ten are genuinely malicious. It catches roughly ten, and it also produces roughly one hundred thousand false alarms. The alerts that matter are lost in the ones that do not, and the failure is not the sensor's accuracy but the ratio of normal to malicious traffic. This is why tuning is the whole job, why untuned systems get ignored, and why "we installed an IDS" is not a security posture.

munotes.in202

How the Scan Is Seen: Intrusion Detection and the Defender's View

Internet background noise. Scanning of public addresses is continuous and automated. Alerting on every scan produces noise and teaches the team to ignore the alerts. The valuable signals are targeted scanning, scanning that follows other reconnaissance, and above all internal scanning, which should almost never happen and is a strong indicator of a compromised host mapping the network.

Evasion. Slow scans spread over days can fall below thresholds; distributed scans from many sources break the one-source pattern; fragmentation and unusual encodings can confuse simple signature matching. Sensors implement countermeasures, and the honest summary is that a patient, distributed, slow attacker is genuinely hard to catch by pattern alone.

Alerts are not response. An alert nobody reads, or reads three days later, has not defended anything. Detection's value is bounded by the response process attached to it.

Tuning, and what to actually alert on

The practical guidance that follows from the limits:

  • Do not alert on every scan of the perimeter. Record it; alert on repeats from the same source, or scans that precede other activity.
  • Do alert on internal scanning, loudly. One workstation contacting many others on many ports is a hallmark of lateral movement.
  • Alert on the abnormal packet types (bare FIN, NULL, XMAS): rare, high-confidence, few false positives.
  • Alert on the composite, not the single event: a scan followed by a connection to a service followed by authentication failures is worth far more than any one of those.
  • Use deconfliction. During an authorised test the tester's source addresses are known, so their traffic can be excluded or tagged, which is the rules-of-engagement item from the authorisation chapter earning its place.
  • Feed detection into response. An alert must reach someone with a procedure.

A worked example

A tester scans a client's perimeter, and afterwards they review what the client's monitoring recorded.

What the client saw:

  • The firewall log recorded 1,340 denied connection attempts from one address in four minutes across 998 distinct ports: unmistakable.
  • The network sensor raised one alert, "TCP port scan detected", at a threshold of 100 connection attempts in 60 seconds.
  • The web server's log contained nothing, because the SYN scan never completed a connection, confirming the application-layer stealth claim exactly.
  • The tester's later XMAS scan raised a second, different alert, on the invalid flag combination, on its very first packet.
  • The tester's slow scan the following day, one probe every 45 seconds, raised no alert, because it stayed under the threshold.
munotes.in203

How the Scan Is Seen: Intrusion Detection and the Defender's View

The findings for the report:

  1. Detection works for ordinary scanning, which is a positive finding and should be recorded as one.
  2. The threshold-based rule is evadable by a slow scan. Recommend rate-independent detection: alert on a source that contacts an unusual number of distinct ports over a long window, not only a short one.
  3. No alert was configured for internal scanning. This is the more serious gap: the perimeter is watched and the interior is not, so an attacker with a foothold could map the network unobserved.
  4. Alerts were raised but nobody acted during the test, since no one contacted the tester. Recommend an escalation procedure, because an alert without response is not a control.

Finding four is the one clients least expect and most need.

What beginners get wrong

  • Believing a half-open scan is undetectable. It avoids application logs and produces the network's most recognisable pattern.
  • Thinking inverse scans are stealthier. They send packets that never occur legitimately and are flagged on a single packet.
  • Assuming an IDS catches everything. The base-rate problem means untuned systems drown real alerts in false ones.
  • Confusing IDS with IPS. One alerts out of band, the other blocks inline, where a false positive becomes an outage.
  • Alerting on all perimeter scanning. It is constant background noise; the signal is targeted, sequenced or internal activity.
  • Ignoring internal scanning. It should essentially never occur and is a strong indicator of compromise.
  • Treating an alert as a defence. Unread or unactioned alerts defend nothing.

Quick revision

  • A scan's shape gives it away: one source, many ports, incomplete connections, a high failure ratio, no application activity. The shape is independent of the flags used.
  • Evasion at one layer is visibility at another: avoiding application logs requires crafted packets, which sensors notice.
  • Evidence lives in firewall logs, network sensors, application logs, host logs, and flow records.
  • Signature detection is precise but limited to known patterns; anomaly detection can find novelty but produces false positives. Both are used together.
  • IDS alerts out of band and cannot break anything; IPS blocks inline, where a false positive is an outage. Network-based sees broadly but not inside encryption; host-based sees one machine deeply.
  • Limits: encryption hides content but not shape; the base-rate problem drowns true alerts unless tuned; internet scanning is constant background noise; slow and distributed scans evade thresholds; an alert without response is not a control.
  • Alert on internal scanning, abnormal packet types, and composite sequences; deconflict authorised testing.
munotes.in204

How the Scan Is Seen: Intrusion Detection and the Defender's View

Test yourself

  1. Why is a SYN scan not stealthy at the network level, despite avoiding application logs?

Because its detectability rests on the pattern rather than the flags: one source contacting many ports in a short time, with connections that never complete and a high ratio of refusals, and no application-layer activity. That shape does not occur in legitimate traffic and is precisely what network sensors are tuned to recognise.

  1. Distinguish signature-based from anomaly-based detection, giving one strength and one weakness of each.

Signature detection matches known patterns: it is precise and explicable with few false positives, but can only find what a rule was written for and may be evaded by small variations. Anomaly detection flags deviation from a learned baseline: it can identify previously unseen activity, but defining normal is difficult and it produces false positives, and a baseline learned while an intruder was present treats the intrusion as normal.

  1. What is the base-rate problem, and why does it dominate the practical value of detection?

Because malicious events are a tiny fraction of total traffic, even a highly accurate sensor generates far more false alarms than true ones: a 99 per cent accurate system over ten million daily events with ten genuine attacks produces around one hundred thousand false alerts. The real alerts are lost among them, so tuning rather than raw accuracy determines whether detection is useful.

  1. What is the essential difference between an IDS and an IPS, and what risk does the latter introduce?

An IDS observes traffic out of band and raises alerts without being able to affect it; an IPS sits inline and can block the traffic it identifies. The risk is that a false positive now blocks legitimate traffic, potentially causing an outage, and that the device's own failure interrupts the path.

  1. Why should internal scanning be alerted on more loudly than perimeter scanning?

Because scanning of internet-facing addresses is continuous automated background noise, so alerting on all of it creates fatigue and trains the team to ignore alerts. Internal scanning, by contrast, should essentially never occur in normal operation, so one host contacting many others across many ports is a strong indicator of a compromised machine performing lateral reconnaissance.

Contents This chapter on its own page

munotes.in205

Chapter Forty-Three

Enumeration and Banner Grabbing

Syllabus topic Module 1, "Enumeration and Service Identification: Study enumeration techniques such as ... service fingerprinting to identify exposed system services"

In one line

Enumeration is the step after scanning: having found open ports, you connect to the services and extract the details they give away, versions, names, shares, users, and the most basic form of it is reading the banner a service announces on connection.

In examination wording: enumeration is the active extraction of information from identified services, including software versions, network shares, user and group names, and system configuration; banner grabbing is the retrieval of the identifying text a service presents upon connection; both require interaction with the target and therefore authorisation.

Scanning against enumeration

ScanningEnumeration
QuestionWhich ports are open?What is behind them, and what will it tell me?
InteractionMinimal: often a single packetA conversation with the service
OutputPort statesVersions, names, shares, users, configuration
Volume of trafficLow per portHigher per service
DetectabilityThe scan patternApplication-level logs, because connections complete

The practical difference is that enumeration completes connections and speaks the application protocol. A SYN scan may leave no application trace; enumeration almost always does, because the service must accept the connection to answer. So enumeration is noisier than scanning, and a tester should expect it to appear in the client's logs.

The legal position is unchanged and worth restating: enumeration is unambiguously interaction with the target's systems, an act under section 43, and is performed only within an authorised scope.

The principle of the block

Every technique in this block and the next three has the same shape: a service answers a question from an unauthenticated stranger that it did not need to answer.

Not one of them is a software flaw. There is no memory corruption, no injection, no exploit. The service is functioning exactly as designed, and the design decided, often decades ago and for good reasons at the time, to be helpful by default.

Two consequences follow, and they run through every chapter in the block:

  • The countermeasures are configuration, not patching. You cannot patch away a service that is doing what it was built to do; you change what it is willing to say and to whom.
  • The findings are frequently serious anyway. A list of valid user names, a set of network shares, a device's full configuration: none required an exploit, and each substantially advances an attacker.

Banner grabbing

The simplest enumeration. Many services, on accepting a connection, send a line identifying themselves before anything else. An FTP server, an SSH server, an SMTP server and a POP3 server all conventionally greet the client; a web server identifies itself in a response header rather than a greeting, which amounts to the same thing.

What a banner typically contains: the product name, very often the version, sometimes the operating system or distribution, and occasionally a hostname or an administrative contact.

munotes.in206

Enumeration and Banner Grabbing

Why the version is the prize, restating the pipeline from the scanning block: product plus version is a query against CVE and the National Vulnerability Database, producing a list of known vulnerabilities with severities. Everything before this narrows the target; the version makes it actionable.

How it is done. Simply connecting to the port and reading what arrives, using any tool that opens a TCP connection. For protocols that do not greet, sending a minimal valid request and reading the response headers does the same job. It requires no special technique, which is why it is the first thing done and the first thing a defender should assume has been done.

Login banners are a separate matter. Some systems display a message before authentication, and a legally useful one states that access is restricted to authorised users, since it removes any argument that access was believed to be permitted. A poorly chosen one says "Welcome" and names the organisation and the system's role, which is an invitation and a disclosure. The content of a pre-authentication banner should be a deliberate decision.

Banner suppression, honestly assessed

The obvious response is to remove the version from the banner, and it is worth being precise about how much that achieves.

What it does. It stops the laziest form of identification and removes the string from automated scans that rely on banners alone. It costs nothing, so it is worth doing.

What it does not do. It does not prevent identification. As the scanning block showed, behavioural fingerprinting determines versions from how a service responds to unusual requests, which options it supports, and the exact wording of its errors, and those differ between releases whatever the banner says. A determined identification will usually succeed.

Where it actively misleads. An administrator who suppresses the banner and believes the service is now protected has substituted a feeling for a control. Worse, banner editing is sometimes used to display a false version, which confuses the organisation's own inventory and vulnerability management more reliably than it confuses an attacker.

The correct ordering, and it is the chapter's central practical point:

  1. Patch. If the running version has no unpatched known flaw, an attacker who identifies it perfectly has gained nothing actionable.
  2. Reduce exposure. A service that need not face untrusted networks should not.
  3. Then suppress banners, as a cheap supplementary measure that raises the attacker's cost slightly.

Banner suppression is obscurity, and obscurity is a valid supplement and an invalid primary control, exactly as the footprint-audit chapter concluded.

What else basic enumeration yields

Beyond the banner, before the protocol-specific chapters:

munotes.in207

Enumeration and Banner Grabbing

Supported options and capabilities. Many protocols will list what they support if asked: which authentication mechanisms, which extensions, which versions of the protocol. This reveals whether weak options are available, and the availability of an obsolete mechanism is a finding in itself.

Error messages. The wording of an error frequently identifies the implementation, and a verbose error may disclose internal paths or component versions.

Default and sample content. A default landing page, an unchanged sample application, or a management interface at a conventional path identifies the product and signals that the deployment was not hardened.

Certificate details. For any service using TLS, the certificate is presented before authentication and contains the subject and alternative names, the issuer, and validity dates. Those host names frequently include internal names, which is the certificate-transparency finding from the footprinting block arriving by a second route. It also reveals expired or self-signed certificates and weak algorithms.

Behaviour differences by input. Whether a service responds differently to a valid and an invalid user name is the user enumeration problem that the LDAP and SMTP chapter develops, and the same logic applies to web login pages.

A worked example

A tester enumerates a host found earlier to have 22, 443 and 8080 open.

Port 22. Connecting yields a greeting naming the SSH implementation and version, and the distribution it was packaged for. Looked up, that version has no unpatched known flaws. The finding is minor: the version is disclosed, and the distribution name narrows the platform.

Port 443. The service does not greet, but the TLS certificate is presented at once. Its subject alternative names list four host names, two of which the tester had not discovered in the earlier reconnaissance, including one containing the word "internal". The response headers name the web server and its version. Two findings: additional hosts disclosed by the certificate, and a version disclosed by the header.

Port 8080. The banner has been removed. But requesting a non-existent path returns a distinctive error page whose wording identifies the product, and requesting the conventional management path returns a login page carrying the product's name and a version in a script path. The finding: banner suppression did not prevent identification, the product is three versions behind, and a management interface is exposed to the internet.

The report's recommendations follow the ordering above: patch the application server (the real control), remove the management interface from internet exposure (reduce the attack surface), review what host names the certificate discloses, and, as a minor note, suppress the web server version. The example also demonstrates the chapter's argument about suppression: the one service that had removed its banner was identified anyway, in two independent ways.

munotes.in208

Enumeration and Banner Grabbing

What beginners get wrong

  • Merging scanning and enumeration. Scanning finds open ports; enumeration converses with the services to extract detail. Versions, shares and user names come from the second.
  • Thinking enumeration is as quiet as scanning. It completes connections and speaks the protocol, so it usually appears in application logs.
  • Overrating banner suppression. It stops lazy identification and is defeated by behavioural fingerprinting. Patch first; suppress as a supplement.
  • Falsifying banners. It confuses the organisation's own inventory more reliably than it confuses an attacker.
  • Forgetting the certificate. It is presented before authentication and frequently discloses internal host names.
  • Treating enumeration findings as low severity because nothing was exploited. A valid user list or an exposed management interface materially advances an attack without any exploit.

Quick revision

  • Scanning finds open ports; enumeration converses with the services to extract versions, names, shares, users and configuration. Enumeration completes connections, so it is noisier and logged.
  • The block's principle: a service answering a stranger a question it need not answer. Not a flaw, so the countermeasure is configuration, not patching.
  • Banner grabbing reads the identifying text a service sends on connection; the version is the prize because it converts to a CVE list.
  • Banner suppression is cheap and worth doing, defeated by behavioural fingerprinting, and dangerous if mistaken for a control. Order: patch, reduce exposure, then suppress.
  • Also yielded: supported options and weak mechanisms, error-message wording, default and sample content, TLS certificate names presented before authentication, and differing responses to valid and invalid users.
  • A pre-authentication login banner should state that access is restricted, and should not name the system's role.

Test yourself

  1. Distinguish scanning from enumeration, and say which is more likely to appear in a target's logs.

Scanning determines which ports are open, typically with minimal interaction; enumeration connects to those services and speaks their protocol to extract versions, shares, user names and configuration. Enumeration is far more likely to be logged, because the connection must complete and the service must process a request in order to answer.

  1. What is the unifying principle of the enumeration techniques, and what follows for the defences?

Each is a service volunteering information to an unauthenticated stranger that it had no need to disclose, and is functioning exactly as designed rather than exhibiting a flaw. It follows that the countermeasures are configuration changes, restricting what the service will say and to whom, rather than patches.

  1. Why is the version string the most valuable item in a banner?

Because CVE records identify vulnerabilities in specific products at specific versions, so the version can be looked up directly to yield a list of known flaws with severities. Earlier steps only narrow the target; the version converts reconnaissance into an actionable list.

munotes.in209

Enumeration and Banner Grabbing

  1. Assess banner suppression as a control.

It is cheap and worth doing, because it defeats identification that relies on banners alone. It is not a control in itself, because behavioural fingerprinting identifies versions from response differences regardless, and it becomes harmful when an administrator treats it as protection or falsifies the version, which misleads the organisation's own inventory more reliably than an attacker. Patching and reducing exposure come first.

  1. Why is a TLS certificate an enumeration source, and what does it disclose?

Because it is presented to any client before authentication. It discloses the subject and subject-alternative host names, which frequently include internal names not otherwise discoverable, together with the issuer, validity dates and the algorithms in use, revealing expired, self-signed or weakly configured certificates.

Contents This chapter on its own page

munotes.in210

Chapter Forty-Four

SNMP Enumeration

Syllabus topic Module 1, "Enumeration and Service Identification: Study enumeration techniques such as SNMP enumeration"

In one line

SNMP exists so administrators can monitor and manage devices over the network, so it holds a great deal of information about them. Access is controlled by a community string, which is effectively a password, and the defaults are "public" and "private", which everybody knows.

In examination wording: the Simple Network Management Protocol allows the monitoring and configuration of network-attached devices; managed devices expose data organised in a Management Information Base, addressed by object identifiers; in versions 1 and 2c, access is authorised only by a community string transmitted in plaintext, and the widespread retention of default community strings permits unauthorised disclosure and, with a read-write string, modification of device configuration.

What SNMP is for

Network administrators need to know whether devices are healthy without logging in to each one. SNMP is the protocol built for that, and it is on almost everything: routers, switches, firewalls, printers, servers, cameras, uninterruptible power supplies.

Three roles:

  • The managed device runs an agent exposing information about itself.
  • The manager (a monitoring system) queries agents and collects the answers.
  • The device may also send unsolicited traps to the manager when something noteworthy happens.

It runs over UDP, normally on port 161 for queries and 162 for traps, which is why the UDP scanning chapter insisted that skipping UDP misses real findings. It is also why the source address of a query can be forged, which matters for amplification later.

The Management Information Base

The information an agent exposes is organised as a tree called the Management Information Base (MIB). Each item has an object identifier (OID), a dotted numeric path through that tree, and a manager asks for an item by its OID.

Standard branches exist that nearly every device implements, and vendors add their own. A walk of the tree, asking for each item in turn, retrieves everything the agent is willing to disclose.

What that typically includes:

CategoryExamples
System identityHostname, a description string naming the operating system and version, location, contact person, uptime
Network configurationEvery interface with its addresses and masks, the routing table, the ARP table
ConnectionsOpen TCP and UDP ports, and on some agents the processes behind them
SoftwareInstalled software and running processes, on host agents
Storage and hardwareDisks, memory, sensors
UsersOn some agents, local user accounts

Read that list against what the earlier chapters worked to obtain. Host discovery, port scanning, service identification, OS fingerprinting and infrastructure mapping all produced, by inference and effort, information that a single SNMP walk may hand over directly and authoritatively. The description string alone often gives the exact operating system and version that fingerprinting could only estimate, and the routing and ARP tables reveal the internal network structure that an external scan cannot see at all.

munotes.in211

SNMP Enumeration

That is why this is a serious finding rather than a hygiene note.

The community string, and the defaults

In SNMP versions 1 and 2c, authorisation rests entirely on a community string sent with the request. There are conventionally two:

  • A read-only community, by default "public".
  • A read-write community, by default "private".

Two properties make this weak:

The defaults are universal knowledge. They are in the specifications, the vendor documentation and every guide. An attacker does not guess; they try the two everybody uses, and a device left at defaults answers.

The string is sent in plaintext. There is no encryption and no challenge. Anyone who can observe the traffic reads the community string, so even a changed string is exposed to a sniffer on the path, which connects to the sniffing chapters later.

The read-write community is the serious one. With read-only access an attacker learns the device inside out. With read-write they can change the configuration: alter routing, modify interface settings, in some cases cause the device to upload its configuration to a server they control or reload a configuration they supply. On a router or firewall that is effectively control of the network path, which makes a default "private" string one of the most severe misconfigurations in this book.

SNMP versions

Know the three, because the answer to "how do we fix this?" is partly "use version 3".

Version 1. The original. Community strings in plaintext, limited data types.

Version 2c. The widely deployed one. Adds bulk retrieval, which makes walking the tree much faster, and keeps the same plaintext community-string model. The "c" stands for community-based, and its security is version 1's.

Version 3. Adds a real security model: user-based authentication with a username and authentication key, integrity protection so messages cannot be altered undetected, and optional encryption of the contents. It also provides view-based access control, so a given user can be restricted to part of the tree.

Version 3 is the answer, and the honest reason it is not universal is that it is more work to configure, older devices may not support it, and monitoring systems must be reconfigured. That inertia is why version 2c persists on networks built years ago.

Why this survives

Worth stating, because it generalises to the whole block.

  • It works. A device answering "public" is monitored correctly by the monitoring system; nothing is broken, so nothing prompts a change.
  • It is on devices nobody administers. Printers, cameras, environmental sensors and power supplies frequently ship with SNMP enabled and defaults set, and they belong to no one in the organisation's inventory. This is the forgotten-asset problem from the footprinting block appearing again.
  • It is invisible. No symptom, no alert, no user complaint.
  • It is not obviously a service. Administrators who would never leave a management web interface open forget that SNMP is one.
munotes.in212

SNMP Enumeration

Countermeasures

In order of effect:

  1. Turn it off where it is not used. The commonest correct answer. Many devices have SNMP enabled by default and nothing is monitoring them.
  2. Change the community strings to values that are long and unguessable, and never reuse one string across the estate, since capturing it once would otherwise expose everything.
  3. Restrict by source address, so the agent answers only the monitoring servers. This is available on nearly all devices and is highly effective.
  4. Restrict by network. SNMP should live on a management network that is not reachable from user networks and certainly not from the internet. An SNMP agent reachable from the internet is a finding regardless of its community string.
  5. Disable read-write entirely unless configuration by SNMP is genuinely required, which for most estates it is not. This removes the severe case.
  6. Use version 3 with authentication and encryption, and view-based access control limiting each user to what they need.
  7. Block 161 and 162 at the perimeter, both directions.
  8. Include SNMP in the asset audit, because the devices that have it are the devices nobody remembers.

A worked example

A tester assesses an internal network segment, having found earlier that UDP 161 responds on several addresses.

  • A core switch answers to "public". A walk returns the hostname, the full software version, every interface with its addresses, the routing table and the ARP table. From the ARP table the tester obtains a list of live hosts on segments they had not scanned, and from the routing table the internal network's structure. Finding: read-only SNMP with a default string on a core network device, disclosing the internal topology.
  • A multifunction printer answers to "public" and additionally to "private". It discloses its configuration including the address of the mail server it uses to send scanned documents and a configured user account. Finding: read-write SNMP with a default string; the device's configuration can be altered by anyone on the network.
  • A server answers to a non-default string that the tester obtains by observing a monitoring query on the network, because version 2c sends it in plaintext. Finding: changing the string is insufficient without version 3 or path protection, since it is exposed to anyone who can observe traffic.
  • A firewall does not answer at all: SNMP is restricted to the monitoring server's address. Recorded as a positive finding, and cited as the model for the rest of the estate.
munotes.in213

SNMP Enumeration

Recommendations, in the chapter's order: disable SNMP on the printer and every device not actually monitored; remove all read-write communities; restrict the remainder by source address to the monitoring servers, as the firewall already does; move management traffic to a separate network; and plan a migration to version 3. The report notes that the printer, an unmanaged device belonging to no team, was the worst case, which is the pattern rather than the exception.

What beginners get wrong

  • Thinking read-only access is harmless. It hands over the system description, interfaces, routing and ARP tables, which is the internal map an external attacker cannot otherwise obtain.
  • Missing that version 2c is not more secure than version 1. It adds bulk transfer and keeps the plaintext community model.
  • Believing a changed community string is sufficient. In versions 1 and 2c it travels in plaintext, so anyone on the path can capture it. Restrict by source and network, and prefer version 3.
  • Forgetting SNMP is a management interface. Administrators who would never expose a management console leave SNMP open because it does not look like one.
  • Skipping UDP in the scan. SNMP lives on UDP 161 and is invisible to a TCP-only assessment.
  • Overlooking unmanaged devices. Printers, cameras and power supplies are where defaults survive, precisely because no team owns them.

Quick revision

  • SNMP monitors and manages devices: agent on the device, manager polling it, traps sent unsolicited. UDP 161 for queries, 162 for traps.
  • Data lives in the Management Information Base, addressed by object identifiers; a walk retrieves everything, typically the system description with OS and version, all interfaces and addresses, routing and ARP tables, open ports, running software and sometimes local users.
  • Authorisation in v1 and v2c is a community string in plaintext; defaults are "public" (read-only) and "private" (read-write). v2c adds bulk transfer, not security. v3 adds user authentication, integrity, encryption and view-based access control.
  • Read-only discloses the internal map; read-write permits configuration change, which on a router or firewall is control of the network path.
  • Countermeasures in order: disable where unused; strong, non-reused strings; restrict by source address; management network only, never internet-facing; disable read-write; move to v3; block 161 and 162 at the perimeter; audit unmanaged devices.

Test yourself

  1. What is a community string, and why are the defaults such a serious problem?

It is the value sent with an SNMP request in versions 1 and 2c that alone authorises access, functioning as a password. The defaults, "public" for read and "private" for read-write, are published in specifications and documentation and known universally, so an attacker does not guess but simply tries them, and any device left at defaults answers.

munotes.in214

SNMP Enumeration

  1. Why is read-only SNMP access still a serious finding?

Because the Management Information Base exposes the system description including operating system and version, every interface and address, the routing table and the ARP table, open ports and often running software. That gives an attacker an authoritative internal map, including hosts and segments an external scan cannot reach, which the rest of the reconnaissance process could only estimate.

  1. How does SNMP version 2c differ from version 1, and does it improve security?

It adds bulk retrieval operations that make walking the tree considerably faster, along with some protocol refinements. It does not improve security: it retains the same community-string model transmitted in plaintext, which is why it is called community-based.

  1. Why is changing the community string insufficient on a version 2c deployment?

Because the string is transmitted in plaintext with every query, so anyone able to observe the traffic, for example through the sniffing techniques covered later, can capture it. Protection therefore requires restricting which sources may query the agent and confining SNMP to a management network, or moving to version 3, which authenticates and can encrypt.

  1. Why are printers, cameras and similar devices the commonest place to find this misconfiguration?

Because they frequently ship with SNMP enabled and default community strings set, they belong to no team in the organisation's inventory, and nothing ever breaks to prompt a review. They are the forgotten-asset problem, and they often expose read-write access, which permits alteration of their configuration.

Contents This chapter on its own page

munotes.in215

Chapter Forty-Five

NetBIOS and SMB Enumeration

Syllabus topic Module 1, "Enumeration and Service Identification: Study enumeration techniques such as ... NetBIOS scanning"

In one line

SMB is how Windows machines share files and printers, and NetBIOS is the older naming layer beside it. Queried by a stranger, they can reveal machine names, the domain, shared folders and user accounts, and historically they have been the route by which the most damaging worms spread.

In examination wording: NetBIOS provides name, session and datagram services for legacy Windows networking; the Server Message Block protocol provides file, printer and named-pipe sharing; enumeration of these services can disclose host and domain names, available shares, and user and group accounts, particularly where anonymous or null-session access is permitted.

What they are, and the ports

NetBIOS is the older mechanism, providing a flat name service for machines on a local network. It survives for compatibility.

SMB is the file-sharing protocol itself, and in modern deployments it runs directly over TCP without needing NetBIOS.

The ports a student must recognise:

PortService
137/UDPNetBIOS name service
138/UDPNetBIOS datagram service
139/TCPNetBIOS session service (SMB over NetBIOS)
445/TCPSMB directly over TCP, the modern path

Seeing 445 open from the internet is, on its own, a finding of substance. Seeing 137 to 139 exposed is worse, since it indicates a genuinely old configuration.

What enumeration yields

Machine and domain names. The NetBIOS name service will return a host's name, the workgroup or domain it belongs to, and the services it is advertising, along with the MAC address on a local segment. That is identity and grouping, handed over without authentication.

Shares. A list of shared folders, including administrative shares. The names alone are informative: a share called Payroll, Backups or Finance tells an attacker where to concentrate, and whether the share is readable is the next question.

Users and groups. This is the most valuable output. Where anonymous access is permitted, enumeration can return the list of local or domain user accounts, sometimes with details such as full names, comments, the account's security identifier, last logon, and whether the password never expires. A list of valid user names converts password attacks from guessing both halves of a credential to guessing one, which is an enormous advantage, and account comments have been known to contain passwords.

Password policy. Minimum length, complexity requirements and, critically, the lockout threshold. Knowing there is no lockout tells an attacker that online password guessing is viable; knowing the threshold tells them how to stay below it.

The null session

The historically important mechanism and the one examiners ask about.

A null session is a connection to the interprocess-communication share with an empty username and empty password. Older Windows versions permitted it by default, because certain legitimate functions between machines in a domain needed unauthenticated access to basic information.

munotes.in216

NetBIOS and SMB Enumeration

The consequence was that an unauthenticated stranger could connect and enumerate shares, users, groups and policy. It became the standard first step against Windows networks.

Modern Windows restricts this substantially: anonymous enumeration is disabled or limited by default, and the relevant policies allow it to be tightened further. But three qualifications keep it examinable and relevant:

  • Legacy systems persist, especially embedded and industrial devices running old Windows versions that cannot be updated.
  • Misconfiguration re-enables it, often to make an old application work.
  • Authenticated enumeration remains possible: an attacker who has obtained any valid low-privileged credential can usually enumerate users, groups and policy fully, which matters because it turns one weak account into a map of every account.

Why this protocol has the worst history

SMB has been the vector for the most damaging self-propagating malware in the field's history, and the pattern is worth understanding rather than memorising.

A worm needs a service that is reachable, present on nearly every machine, and exploitable without authentication. SMB has repeatedly satisfied all three: it is on every Windows machine, it is enabled by default on internal networks, and vulnerabilities in its implementation have permitted remote code execution without credentials. Add that internal networks are frequently flat, and a single compromised machine can reach every other machine's port 445 directly.

The lesson generalises beyond SMB, and it is the reason this chapter sits where it does: a service that is ubiquitous, enabled by default, and reachable across a flat internal network is the ideal propagation path. The defences that follow are therefore not only about enumeration; they are about limiting how far an internal compromise can spread.

Countermeasures

Never expose SMB or NetBIOS to the internet. Block 137, 138, 139 and 445 at the perimeter in both directions. This is not a hardening nicety; it is the single most important line in the chapter. Outbound blocking matters too, because a client tricked into connecting to an external SMB server can leak authentication material.

Disable NetBIOS over TCP/IP where nothing requires it, leaving SMB on 445 alone.

Restrict anonymous access. Ensure the policies that prevent anonymous enumeration of shares, users and policy are set, and do not relax them for a legacy application without compensating controls.

Use SMB version 3 and disable version 1. SMBv1 is obsolete, was the vehicle for the worst worm incidents, and should be removed rather than merely discouraged. SMBv3 adds signing, which prevents tampering and relay attacks, and encryption, which protects file contents in transit on the internal network.

Require SMB signing, which defeats a class of relay attack in which an attacker forwards a victim's authentication to another machine.

munotes.in217

NetBIOS and SMB Enumeration

Apply least privilege to shares. Each share visible and accessible only to those who need it, with the principle that a user should not be able to enumerate the existence of shares they cannot use. Remove unused shares, which accumulate.

Segment the network. Since the propagation pattern depends on every machine being able to reach every other machine's port 445, segmentation is what converts a worm outbreak from an estate-wide event into a contained one. Host firewalls that block inbound SMB between workstations are highly effective, because workstations almost never need to share files directly with each other.

Patch promptly. The specific flaws that enabled the worst incidents were patched before the outbreaks; the damage was done to systems that had not applied the fix.

Monitor. Internal SMB scanning, and one host connecting to many others on 445, is a hallmark of both worm propagation and lateral movement, and is among the highest-value internal alerts an organisation can configure.

A worked example

A tester assesses an internal network with authorisation.

  • From the internet, 445 is correctly blocked at the perimeter. Positive finding.
  • Internally, a file server permits an unauthenticated connection to list shares. Fourteen shares are visible, including HR-Confidential and Backup. Attempting to read them requires credentials, so the disclosure is of names rather than contents. Finding: share enumeration is permitted anonymously, which tells an attacker exactly where to aim.
  • A legacy industrial control machine running an old Windows version permits a null session, returning the full local user list with comments, one of which reads "temporary password Summer2019". Finding: anonymous enumeration and a credential in an account comment, the more serious of the two.
  • Using a low-privileged test account supplied by the client, the tester enumerates the domain and obtains the complete user list and the password policy, which shows no account lockout threshold. Finding: any valid credential yields a full user list, and the absence of lockout makes online password guessing viable.
  • Workstations accept inbound connections on 445 from other workstations. Finding: no host-level segmentation, so a single compromised workstation can reach every other directly, which is the worm propagation path.

Recommendations in priority order: set a lockout threshold and review the exposed credential immediately; block inbound SMB between workstations with host firewalls; restrict anonymous share and user enumeration; isolate the legacy control machine on its own segment since it cannot be updated; disable SMBv1 and require signing; and review share permissions so that names are not visible to those without access.

The finding that will surprise the client is the last of the five: the perimeter was correct and the interior was flat, which is the pattern the engagement-types chapter predicted when it argued that internal testing is usually more revealing than external.

munotes.in218

NetBIOS and SMB Enumeration

What beginners get wrong

  • Thinking SMB needs NetBIOS. Modern SMB runs directly on 445; NetBIOS on 137 to 139 is legacy and should usually be disabled.
  • Treating share-name disclosure as trivial. Names tell an attacker where the valuable data is and where to concentrate credential attacks.
  • Believing null sessions are a solved historical problem. They persist on legacy and embedded systems, and any valid low-privileged credential usually restores full enumeration.
  • Underestimating a user list. It halves the password-attack problem, and account comments have contained passwords.
  • Ignoring the lockout policy as an enumeration finding. Learning that no lockout exists is what makes online guessing worth attempting.
  • Blocking SMB inbound only. Outbound blocking matters too, because a client induced to connect outward can leak authentication material.
  • Leaving SMBv1 enabled "for compatibility". It was the vehicle for the worst incidents in the field and should be removed.

Quick revision

  • Ports: 137/UDP name, 138/UDP datagram, 139/TCP session (SMB over NetBIOS), 445/TCP SMB direct. 445 exposed to the internet is a finding in itself.
  • Yields: machine and domain names, share names, user and group accounts with details, and the password policy including the lockout threshold.
  • A null session is a connection with empty username and password, historically permitting full anonymous enumeration; restricted in modern Windows but alive on legacy and embedded systems, and any valid low-privileged credential usually restores it.
  • Worst history in the book: ubiquitous, default-enabled and reachable across flat internal networks, which is the ideal worm propagation path.
  • Countermeasures: block 137 to 139 and 445 at the perimeter both ways; disable NetBIOS over TCP/IP; restrict anonymous enumeration; disable SMBv1, use SMBv3 with signing and encryption; least privilege on shares; segment, including host firewalls blocking workstation-to-workstation SMB; patch promptly; and alert on internal 445 sweeps.

Test yourself

  1. Which ports carry NetBIOS and SMB, and which single observation is a finding on its own?

NetBIOS uses 137/UDP for names, 138/UDP for datagrams and 139/TCP for sessions; SMB runs directly over 445/TCP in modern deployments. Port 445 reachable from the internet is a finding on its own, and exposure of 137 to 139 indicates an even older configuration.

  1. What is a null session, and why does it still matter despite modern defaults?

A connection to the interprocess-communication share using an empty username and password, which historically permitted anonymous enumeration of shares, users, groups and password policy. It still matters because legacy and embedded systems that cannot be updated continue to permit it, because misconfiguration re-enables it for old applications, and because any valid low-privileged credential typically restores full enumeration anyway.

  1. Why is obtaining a list of valid user names so valuable to an attacker?
munotes.in219

NetBIOS and SMB Enumeration

Because it reduces a credential attack from guessing both the username and the password to guessing only the password against accounts known to exist. Combined with knowledge of the password policy, particularly the absence of a lockout threshold, it makes online guessing practical, and account comments have been found to contain passwords outright.

  1. Why has SMB been the vector for the most damaging worms, and what does that imply for defence?

Because it satisfies every requirement for propagation: it is present on virtually every Windows machine, enabled by default internally, and has had vulnerabilities permitting remote code execution without authentication, while internal networks are typically flat so every machine can reach every other on port 445. It implies that segmentation, including host firewalls preventing workstation-to-workstation SMB, is what converts an outbreak from estate-wide to contained.

  1. Name four countermeasures for SMB exposure, in order of importance.

Block 137 to 139 and 445 at the internet perimeter in both directions; segment internally so hosts cannot reach each other's SMB ports unnecessarily; disable SMBv1 and require SMB signing with SMBv3; and restrict anonymous enumeration of shares, users and policy, together with least-privilege share permissions and prompt patching.

Contents This chapter on its own page

munotes.in220

Chapter Forty-Six

LDAP, SMTP and NTP Enumeration

Syllabus topic Module 1, "Enumeration and Service Identification: Study enumeration techniques"

In one line

LDAP is the organisation's directory, so it holds every user. SMTP can be made to confirm whether an address exists, which is user enumeration by a different route. NTP distributes time, and a time service that answers strangers reveals hosts and can be abused for amplification.

In examination wording: the Lightweight Directory Access Protocol provides access to directory information including users, groups and organisational structure; the Simple Mail Transfer Protocol may disclose the validity of addresses through its command responses; the Network Time Protocol may disclose the hosts with which a server communicates and can be used as an amplification vector; each may be queried by an unauthenticated party where access controls are not applied.

LDAP: the directory

What it is. LDAP is the protocol for querying a directory service: a hierarchical database of an organisation's people, groups, computers and resources. It is the query language of enterprise identity systems, and on a Windows network the directory behind it is the domain controller's.

Ports: 389/TCP for LDAP, 636/TCP for LDAPS (LDAP over TLS). Larger directory deployments also use 3268 and 3269 for a forest-wide catalogue.

What it exposes. The directory exists to be queried, so a successful query can return a great deal:

  • Every user account, with the attributes stored on it: full name, job title, department, manager, telephone, email address, and often when the password was last set and whether it ever expires.
  • Groups and membership, which is the map of privilege. A group called "Domain Admins" and its members is the list of the most valuable accounts in the organisation.
  • Computers, with their operating-system versions, which is an inventory an external scan cannot obtain.
  • Organisational structure, since the directory is arranged by department and location.
  • Sometimes descriptions and comments on accounts, which have been found to contain passwords or the reason an account was created.

The failure mode. Anonymous bind, a connection with no credentials. Some directories permit it, either by configuration or to support an application that needed it. Where anonymous bind is allowed and the access controls are permissive, an unauthenticated stranger can read the directory.

Even where anonymous bind is refused, the position is often not much better: any valid credential usually suffices to read most of the directory, because directories are designed so that ordinary users can look one another up. So a single phished or guessed low-privileged password commonly yields the full user list, the group memberships and the privileged accounts, which is exactly the escalation-planning information an attacker wants.

Countermeasures. Disable anonymous bind. Require LDAPS so that queries and credentials are not sent in plaintext, and require signing where available. Apply access controls so that ordinary accounts can read only what they need rather than the whole directory, and in particular restrict who can enumerate privileged group membership. Do not store anything sensitive in description fields. Restrict directory ports to internal networks and never expose them to the internet. Monitor for bulk directory reads, since a normal user looks up a colleague occasionally and an attacker enumerates everything at once, which is a detectable pattern.

munotes.in221

LDAP, SMTP and NTP Enumeration

SMTP: confirming who exists

What it is. The protocol that transfers mail between servers, on 25/TCP, with 587 for message submission and 465 for implicit TLS.

How it leaks. Three commands, historically, and one general behaviour.

VRFY asks the server to verify that a mailbox exists. EXPN asks it to expand a mailing list into its members. Both were designed to be helpful to administrators and both directly enumerate valid addresses. Modern servers usually disable them, and finding either enabled is an immediate finding.

RCPT TO, the command naming a message's recipient, is the one that cannot simply be disabled, because it is how mail is delivered. If the server responds differently to a valid and an invalid recipient, accepting one and rejecting the other with "no such user", then an attacker can test addresses one at a time and learn which exist. This is the general case and the harder problem.

Why it matters. It converts a guessed user list into a confirmed one. Recall the OSINT chapter: one published address reveals the email format, and the format plus a staff list from a professional network produces a constructed list of probable addresses. SMTP enumeration confirms which of those are real, and a confirmed list is what feeds password spraying and targeted phishing.

User enumeration as a general idea, because this is where the book introduces it. Any system that behaves differently for a valid and an invalid identity leaks the identity. It appears in:

  • mail servers, as here;
  • login pages that say "no such user" rather than "invalid username or password";
  • password reset forms that confirm whether an address is registered;
  • registration forms that reject an already-used address;
  • and timing, where a system that checks a password only for existing users takes measurably longer for a valid name, leaking the same information without any difference in wording.

The countermeasure is the same everywhere and worth stating once: respond identically whether or not the identity exists, in wording, in status code and, where it matters, in timing. This reappears in the authentication chapters of Module 2.

Countermeasures for SMTP specifically. Disable VRFY and EXPN. Configure the server so that rejection for an unknown recipient is indistinguishable from other rejections, or accept and discard, accepting the trade-off that this loses the immediate bounce that legitimate senders find useful. Apply rate limiting and connection throttling, so that testing thousands of addresses is impractical. Require authentication for submission, and never operate an open relay, a server that will forward mail for anyone, which is both an abuse vector and a reputational disaster.

munotes.in222

LDAP, SMTP and NTP Enumeration

NTP: time, hosts and amplification

What it is. The protocol that synchronises clocks, on 123/UDP.

Why time matters for security, which students under-appreciate: certificate validity is a time comparison, so a host with a badly wrong clock may accept an expired certificate or reject a valid one; authentication protocols that rely on timestamps to prevent replay fail if clocks drift; and log correlation across hosts during an investigation is impossible if their timestamps disagree. Time is a security dependency, not an administrative convenience.

What enumeration yields. Query modes exist that ask a server about its own state, and where they are enabled a server may return the list of peers it synchronises with, which discloses internal hosts, and details of its own software version and configuration. This is a modest disclosure compared with LDAP, and it is included because it maps internal infrastructure from outside.

The amplification problem, which is the serious part. Some older or misconfigured NTP servers support a monitoring command that returns a long list of recent clients in response to a very short request. Because NTP runs over UDP, an attacker can forge the source address to be a victim's, so the large reply is sent to the victim. The ratio of response size to request size makes this a powerful amplification vector, and it is one of the reflectors named in the denial-of-service chapter.

Note the shape, because it is the general amplification pattern: a connectionless protocol, a small request, a large reply, and no verification of the requester's address.

Countermeasures. Disable the monitoring and query commands that return client lists or server state to strangers. Restrict which sources may query the server at all, so it serves only the organisation's own hosts. Keep the server updated, since the worst amplification behaviours were addressed by later versions. Block 123/UDP inbound at the perimeter for servers that need not be public, and, on the wider principle, implement anti-spoofing filtering so that packets with forged source addresses cannot leave your network, which is the control that starves all amplification attacks at source.

A worked example

A tester enumerates an internal environment and an external perimeter.

Internally, the directory permits anonymous bind. A query returns 412 user accounts with full names, titles and departments, the membership of the administrative groups (nine accounts), and 180 computer objects with their operating-system versions, of which eleven run an unsupported version. Findings: anonymous directory read; a published list of the nine most valuable accounts; and an inventory revealing eleven unsupported machines the client had not recorded.

munotes.in223

LDAP, SMTP and NTP Enumeration

Externally, the mail server has VRFY disabled, which is correct, but responds to RCPT TO for an unknown recipient with a distinct "user unknown" rejection. The tester takes twenty constructed addresses from the earlier OSINT work and confirms fourteen. Finding: address validity is disclosed, converting a guessed list into a confirmed one.

Also externally, an NTP server answers a monitoring query with a list of recent clients, disclosing eleven internal addresses and confirming it can be used as an amplification reflector against third parties. Finding with two aspects: internal disclosure, and the client's server being usable to harm others.

Recommendations: disable anonymous bind and restrict directory reads, particularly of privileged group membership; make unknown-recipient rejection indistinguishable and rate-limit connections; disable the NTP monitoring command and restrict the server to internal clients; and implement egress anti-spoofing filtering. The report notes that the NTP finding is unusual in that its main victim would be somebody else, which is a category of risk organisations habitually ignore.

What beginners get wrong

  • Thinking LDAP is safe because anonymous bind is disabled. Directories are built so ordinary users can look each other up, so one low-privileged credential commonly yields the full user and group map.
  • Treating the user list as low severity. It is the map of privilege: group membership names the accounts worth attacking.
  • Assuming disabling VRFY and EXPN solves SMTP enumeration. RCPT TO cannot be removed, so the real fix is responding identically to valid and invalid recipients, plus rate limiting.
  • Missing user enumeration elsewhere. Login, reset and registration pages, and response timing, leak the same information; the answer is always identical responses.
  • Dismissing NTP as unimportant. Wrong time breaks certificate validation, replay protection and log correlation, and an exposed server can be used to attack third parties.
  • Forgetting anti-spoofing. Amplification depends on forged source addresses; egress filtering starves every such attack at source.

Quick revision

  • LDAP (389, LDAPS 636): the directory. Discloses all users with attributes, groups and membership (the privilege map), computers with OS versions, and structure. Fails through anonymous bind, and usually yields to any valid credential. Fix: no anonymous bind, LDAPS and signing, access controls limiting ordinary users, no secrets in descriptions, internal only, alert on bulk reads.
  • SMTP (25, 587, 465): VRFY verifies a mailbox and EXPN expands a list, both to be disabled; RCPT TO cannot be, so differing responses for valid and invalid recipients leak validity. It confirms the guessed address list from OSINT.
  • User enumeration generally: any system responding differently, in wording, status or timing, for a valid identity leaks it. Login, reset and registration pages included. Fix: respond identically.
  • NTP (123/UDP): time underpins certificate validity, replay protection and log correlation. Query modes may disclose peers and clients; a short request yielding a long client list over UDP makes it a major amplification reflector. Fix: disable monitoring queries, restrict sources, update, and deploy anti-spoofing egress filtering.
munotes.in224

LDAP, SMTP and NTP Enumeration

Test yourself

  1. Why does disabling anonymous bind not make an LDAP directory safe from enumeration?

Because directories are designed so that ordinary users can look one another up, so read access is typically granted broadly to authenticated accounts. A single low-privileged credential, obtained by phishing or guessing, therefore commonly yields the full user list, group memberships including privileged groups, and computer objects.

  1. Which SMTP commands directly enumerate users, and why is disabling them insufficient?

VRFY, which verifies whether a mailbox exists, and EXPN, which expands a mailing list into its members. Disabling them is insufficient because RCPT TO, which names a message's recipient, is essential to mail delivery and cannot be removed; if the server rejects unknown recipients distinguishably, address validity is still disclosed one address at a time.

  1. State the general principle of user enumeration and the countermeasure.

Any system that behaves differently for a valid and an invalid identity discloses which identities exist, whether through the wording of a message, a status code, or measurable differences in response timing. The countermeasure is to respond identically in all respects regardless of whether the identity exists, and to rate-limit attempts.

  1. Why is accurate time a security requirement rather than an administrative convenience?

Because certificate validity is determined by comparing dates against the clock, so a badly wrong clock causes valid certificates to be rejected or expired ones accepted; because authentication protocols using timestamps to prevent replay fail when clocks drift; and because correlating logs across hosts during an investigation is impossible if their timestamps disagree.

  1. What makes NTP an amplification vector, and what control addresses amplification generally?

That it runs over connectionless UDP with no verification of the requester's address, and that some servers answer a very short monitoring request with a long list of recent clients, so an attacker forging a victim's source address causes a large reply to be sent to that victim. Generally, anti-spoofing egress filtering, which prevents packets with forged source addresses leaving a network, starves all such attacks at their source.

Contents This chapter on its own page

munotes.in225

Chapter Forty-Seven

Enumeration Countermeasures: What to Close

Syllabus topic Module 1, "Enumeration and Service Identification: ... to identify exposed system services"; Course Outcome 5

In one line

Every finding in this block was a service answering a stranger. The fixes are all configuration, they are all cheap, and the reason they are still found is that nothing breaks when they are wrong, so nobody notices.

In examination wording: countermeasures against enumeration comprise reducing the number of exposed services, restricting each service to the networks and identities that require it, removing default credentials and permissive defaults, ensuring services do not disclose more than necessary to unauthenticated parties, and monitoring for the access patterns characteristic of enumeration.

The common pattern

Look back over the block and every finding has the same three properties.

It was a default. A community string of "public". Anonymous bind permitted. Null sessions allowed. A monitoring query enabled. Nobody chose these; they arrived with the product and survived.

It caused no symptom. The device was monitored correctly, the application worked, the mail was delivered. Operations had no reason to look, because nothing was broken. This is the single most important sentence in the chapter: misconfigurations that produce no symptom are invisible to everyone except an assessment.

It was on something unowned. The printer, the legacy control machine, the old server, the appliance. The systems with the worst configurations are consistently the ones with no named owner, which is the finding the footprint-audit chapter predicted.

So the countermeasures below are technical, and the reason they are not already applied is organisational.

The countermeasures, ranked by how often they are found wrong

1. Services exposed that need not be. The most common finding overall. SNMP enabled on devices nothing monitors, SMB reachable between workstations that never share files with each other, a management interface on the internet, a directory port reachable from a user network.

The fix is to reduce the number of listening services and the networks they listen to, in that order: turn off what is unused, then bind what remains to the interfaces and networks that need it, then filter at the perimeter and between segments. Every service removed is a service that cannot be enumerated, misconfigured or exploited, and it removes a future patching obligation as well.

2. Default credentials and default community strings. "public", "private", vendor default passwords on appliances and management interfaces. Universally documented and therefore not a guess.

The fix is an inventory-driven sweep: for every device, what credentials does it ship with, and have they been changed? This must include the devices nobody owns, which is where the defaults survive.

3. Anonymous and unauthenticated access. Null sessions, anonymous LDAP bind, anonymous FTP, unauthenticated management endpoints, share lists readable without credentials.

The fix is to require authentication for anything that is not deliberately public, and to check what an unauthenticated connection can still obtain after that, since some services disclose a useful amount before any credential is presented.

munotes.in226

Enumeration Countermeasures: What to Close

4. Services disclosing more than they need to. Version banners, verbose errors, VRFY and EXPN, NTP monitoring queries, user-enumeration differences between valid and invalid identities, and certificate names revealing internal hosts.

The fix is per-service and cheap, with the ordering from the banner chapter: patch first, reduce exposure second, reduce disclosure third. The one item in this group that is a real control rather than obscurity is identical responses for valid and invalid identities, because user enumeration genuinely changes the economics of a password attack.

5. Over-broad read access for authenticated users. The subtler finding, and the one clients least expect. Anonymous access is refused and then any ordinary account can read the entire directory, enumerate every share name, or list every user. One phished low-privileged credential then yields the full map of the organisation, including which accounts are privileged.

The fix is least privilege applied to reading, not only to writing. Ordinary users rarely need to enumerate every account, every group membership and every share; they need to find specific colleagues and reach specific resources.

6. Obsolete protocol versions left enabled. SMBv1, SNMPv1 and v2c, LDAP without TLS, plaintext protocols generally.

The fix is to disable rather than deprecate. A protocol version that remains enabled will be used, by an old client or by an attacker who requests it deliberately, so removal is the control.

7. No monitoring of enumeration patterns. Enumeration has a recognisable shape, and almost nobody alerts on it.

The fix is to alert on bulk directory reads, on one host connecting to many others on SMB ports, on repeated SMTP recipient rejections from a single source, and on SNMP queries from sources other than the monitoring servers. These are low-noise, high-value internal alerts, and the last is essentially free.

A checklist by service

For revision, the same content arranged the other way.

ServiceClose this
SNMPDisable where unmonitored; change and do not reuse community strings; remove read-write; restrict by source address; management network only; move to v3; block 161 and 162 at the perimeter
SMB and NetBIOSBlock 137 to 139 and 445 at the perimeter both ways; disable NetBIOS over TCP/IP; restrict anonymous enumeration; disable SMBv1; require signing; least privilege on shares; segment, including host firewalls between workstations
LDAPDisable anonymous bind; require LDAPS and signing; restrict what ordinary accounts may read, especially privileged group membership; no secrets in description fields; internal only; alert on bulk reads
SMTPDisable VRFY and EXPN; make unknown-recipient rejection indistinguishable; rate limit; require authentication for submission; never an open relay
NTPDisable monitoring and state queries; restrict querying sources; update; block inbound 123 where not needed; deploy anti-spoofing egress filtering
All servicesPatch; suppress versions as a supplement; generic errors; TLS where credentials or data travel; identical responses for valid and invalid identities
munotes.in227

Enumeration Countermeasures: What to Close

The organisational half

Because the technical fixes are easy and still not applied, the chapter ends where the audit chapter did.

Ownership. Every device and service has a named owner, or it is decommissioned. An unowned system will not be patched, monitored, reviewed or retired.

Inventory. The countermeasures above are impossible to apply to systems you do not know you have. The footprint audit and the internal sweeps are how the inventory is corrected.

A build standard. New systems should arrive hardened, with defaults changed and unnecessary services disabled, because fixing configuration after deployment is far harder than never shipping it wrong.

Periodic re-testing. Configuration drifts: a service is re-enabled for a project, a rule is widened under time pressure and never narrowed, a new appliance arrives with defaults. The same enumeration run every few months, by the organisation against itself, catches it.

A worked example

A team acts on an assessment covering the whole block. Their plan, in the chapter's order:

  1. Reduce exposure. Host firewalls block inbound SMB between workstations; SNMP is disabled on 34 devices that nothing monitors; the application-server management interface is removed from the internet. Largest risk reduction, and it required no purchase.
  2. Kill defaults. A sweep of every device in the inventory for default credentials and community strings finds eleven, including the printer with the read-write string.
  3. Close anonymous access. Anonymous LDAP bind disabled; anonymous share enumeration restricted; the legacy control machine isolated on its own segment because it cannot be changed.
  4. Reduce disclosure. VRFY and EXPN disabled; unknown-recipient responses made uniform; NTP monitoring query disabled; version banners suppressed as a minor item.
  5. Restrict authenticated reads. Ordinary accounts can no longer enumerate privileged group membership or list every share.
  6. Remove obsolete versions. SMBv1 disabled estate-wide; SNMP v1 and v2c retired where v3 is supported.
  7. Add monitoring. Alerts for SNMP from unexpected sources, bulk directory reads, and internal SMB sweeps.
  8. Fix the cause. Every device gets a named owner; the build standard is updated; the enumeration sweep is scheduled quarterly.

Step eight is what stops the list being needed again in two years, and it is the step most often omitted.

What beginners get wrong

  • Treating these as low-severity hygiene. A user list, a share map, a routing table or a read-write management string materially advances an attack without any exploit.
  • Fixing findings and not the cause. The same defaults return on the next device unless ownership, inventory and the build standard change.
  • Suppressing banners and calling the service hardened. Obscurity is a supplement; patching and reducing exposure are the controls.
  • Stopping at anonymous access. The subtler finding is that any ordinary credential reads everything.
  • Deprecating obsolete protocols instead of disabling them. If it is enabled, it will be used.
  • Assuming operations will notice. None of these produces a symptom, which is exactly why they survive.
  • Ignoring unowned devices. They hold the worst configurations, for the same reason nobody found them.
munotes.in228

Enumeration Countermeasures: What to Close

Quick revision

  • Every finding in the block was a default, produced no symptom, and sat on something unowned. That is why the fixes are cheap and still not applied.
  • Ranked by prevalence: (1) services exposed that need not be; (2) default credentials and community strings; (3) anonymous or unauthenticated access; (4) services disclosing more than necessary; (5) over-broad read access for ordinary authenticated users; (6) obsolete protocol versions still enabled; (7) no monitoring of enumeration patterns.
  • Ordering within disclosure: patch, reduce exposure, then reduce disclosure. The exception that is a real control is identical responses for valid and invalid identities.
  • The organisational half: named ownership, an accurate inventory, a hardened build standard, and periodic re-testing, because configuration drifts.

Test yourself

  1. What three properties do almost all enumeration findings share, and what follows?

They are vendor or protocol defaults that nobody changed; they produce no symptom, so ordinary operations never discover them; and they sit on systems with no named owner. It follows that although the technical fixes are cheap configuration changes, the reason they remain unapplied is organisational, so ownership and inventory must be fixed as well as the settings.

  1. Which countermeasure gives the greatest risk reduction, and why?

Reducing the number of exposed services and the networks they are reachable from. A service that is disabled, or bound only to the network that needs it, cannot be enumerated, cannot be misconfigured and cannot be exploited, and it removes a future patching obligation as well.

  1. Why is restricting anonymous access insufficient on a directory or file server?

Because read access is typically granted broadly to all authenticated users, so any single low-privileged credential obtained by phishing or guessing still yields the full user list, group memberships including privileged groups, and share names. Least privilege must therefore be applied to reading, not only to writing.

  1. Which disclosure countermeasure is a genuine control rather than obscurity, and why?

Responding identically to valid and invalid identities, in wording, status and timing. Unlike banner suppression, which behavioural fingerprinting defeats, it removes information an attacker cannot obtain elsewhere and materially changes the economics of a password attack by preventing the confirmation of which accounts exist.

munotes.in229

Enumeration Countermeasures: What to Close

  1. Why must obsolete protocol versions be disabled rather than merely discouraged?

Because a version that remains enabled will be negotiated, either by an old client that defaults to it or by an attacker who deliberately requests it in order to obtain the weaker protections. Removal is the only reliable control, which is why SMBv1 should be disabled rather than deprecated and SNMP v1 and v2c retired where v3 is available.

Contents This chapter on its own page

munotes.in230

Chapter Forty-Eight

System Hacking and Privilege Escalation

Syllabus topic Module 1, "System Hacking and Privilege Escalation Concepts: Analyze ... privilege escalation techniques ... from a defensive perspective"

In one line

System hacking is what happens after an attacker gets in: turning a limited foothold into control. Its engine is privilege escalation, and because almost every serious compromise needs it, a defender who blocks it makes a breach survivable.

In examination wording: system hacking encompasses gaining access to a host and subsequently increasing the level of control obtained; privilege escalation is the acquisition of rights beyond those originally granted, classified as vertical where the attacker moves to a higher privilege level and horizontal where they access another principal's resources at the same level.

The shape of a compromise

An attacker rarely arrives as an administrator. The realistic entry points give very little:

  • a web application flaw, giving them the rights of the account the web server runs as;
  • a phished credential for an ordinary user;
  • a compromised workstation, with that employee's rights;
  • a weak service account on one machine.

From any of those the attacker can do something, but not much. They cannot read other users' data, install what they like, disable the defences or reach the rest of the network freely. The foothold is real and it is narrow.

Privilege escalation is what makes it wide. With administrative rights on a host the attacker can read everything on it, install software, stop security tools, harvest credentials held in memory, and use that machine as a base to reach others. The difference between a contained incident and a serious breach is usually this one step.

That is why the chapter matters for defence. You cannot guarantee that no attacker ever gets a foothold, because foothold routes include a user clicking a link. You can make the next step hard, and if you do, the foothold stays a foothold.

Vertical and horizontal

Vertical escalation, also called elevation of privilege, is moving up: an ordinary user becoming an administrator, or a limited service account gaining system rights. This is the dangerous form and the one meant when the term is used without qualification.

Horizontal escalation is moving sideways: accessing another principal's data or account at the same privilege level, for example one customer reading another's records, or one employee reading a colleague's files. No privilege level was gained, and the confidentiality breach may be just as serious. In web applications this is the broken access control category that leads the OWASP list in Module 2.

Students should also know lateral movement, which is often confused with horizontal escalation but is different: lateral movement is spreading to other machines, typically with credentials or trust obtained from the first. Horizontal escalation is about identities on the same system; lateral movement is about hosts across the network.

munotes.in231

System Hacking and Privilege Escalation

The routes, at concept level

Escalation is a family rather than a single technique, and every member corresponds to something a defender decided or neglected.

Missing patches. A known flaw in the operating system, a driver or a privileged service allows a local user to execute code at a higher level. The flaw is public, has a CVE, and has a vendor fix. Unpatched, it is an open staircase. This is the most direct route and the most straightforwardly preventable.

Weak permissions on privileged things. Anything that runs with high privilege but depends on something a low-privileged user can change: a service whose program file is writable by users, a scheduled task running a script in a writable directory, a configuration file that a privileged process reads and a user can edit. The attacker does not need a vulnerability; they substitute their own content into a privileged context. The rule: a privileged process must not read or execute anything a lesser user can modify.

Excessive privileges already granted. The commonest and most avoidable of all. If ordinary user accounts are administrators, or a service runs as system when it needs to read one directory, there is nothing to escalate: the attacker already has what they wanted. Much "privilege escalation" in real incidents is simply the discovery that no escalation was required.

Stored credentials. Passwords, keys and tokens left in files a lesser user can read: scripts, configuration files, deployment tooling, command history, unattended-installation files, and scheduled-task definitions. The attacker does not escalate; they find a better identity and use it.

Credential material in memory. On a compromised host, an attacker with sufficient rights can often recover credentials or authentication tokens that other users' sessions have left in memory, which is how a single compromised machine yields credentials belonging to whoever recently logged in, including administrators. This is the route that makes it dangerous for administrators to log in to ordinary workstations.

Default and weak credentials on local services and management interfaces, which is the enumeration block's finding appearing again as an escalation route.

Abuse of legitimate privileges. Some accounts hold rights that permit escalation by design, for example the ability to install drivers, debug other processes, back up any file, or manage a service. Granting such a right is granting a path to administrator, and administrators frequently do not realise it.

Notice that only the first is a software vulnerability. The rest are configuration, provisioning and hygiene, which is why MU's "defensive perspective" framing is apt: escalation is usually a defender's oversight rather than an attacker's cleverness.

The defences

MU asks for the defensive reading, so this is the heart of the chapter.

Least privilege, which outranks everything else here. Every account, service and process receives the minimum rights it needs. Ordinary users are not administrators; applications run as dedicated accounts with narrow rights; databases grant each application access only to its own data. Least privilege does not prevent the initial breach. It ensures the breach lands somewhere with little power and leaves a wall to climb, and it is what converts "an attacker got in" into a contained incident.

munotes.in232

System Hacking and Privilege Escalation

Separate administrative accounts. An administrator uses an ordinary account for daily work and a separate account for administration, and crucially does not use administrative credentials on ordinary workstations, because of the credentials-in-memory route above. This is the control that most often blocks the path from one compromised workstation to the whole estate.

Patch promptly, prioritised by exposure and severity, which closes the published staircases.

Correct permissions. Audit for privileged processes depending on user-writable files, directories and registry locations. This class is findable by automated checking and is repeatedly found in assessments.

No stored secrets. Credentials belong in a secret-management system, not in scripts and configuration. Where a file must hold one, its permissions must exclude ordinary users, and the secret must be rotated when someone leaves.

Application allow-listing, so unapproved programs cannot run, which blocks many escalation tools before they start.

Monitoring for the signs. Escalation is noisy if anyone is watching: a normal account suddenly performing administrative actions, new accounts created, group memberships changed, services installed, security tooling stopped, or unusual access to credential stores. This belongs to the defender's-mirror chapter and is developed further in the persistence chapter.

A worked example, read as a defender

An attacker obtains the credentials of one ordinary employee through phishing and logs in to a workstation remotely. Trace how far they get, depending on choices made earlier:

The organisation's earlier decisionConsequence
Users are local administrators "for convenience"No escalation needed. The attacker already controls the machine
Users are not administrators, but the machine is missing a patched local flawThe attacker escalates and controls the machine
Patched, but a service runs from a user-writable directoryThe attacker replaces the file and escalates at the next start
Patched and permissions correct, but a script in a shared folder contains an administrative passwordThe attacker takes a better identity without escalating at all
All of the above closed, but an administrator logged in to this workstation yesterdayThe attacker may recover that credential from memory and escalate to the estate
All closed, and administrators never log in to workstationsThe attacker remains an ordinary user on one machine

The bottom row is the objective. Every row above it is a decision that was made before the attack, which is the chapter's argument in a table.

munotes.in233

System Hacking and Privilege Escalation

What beginners get wrong

  • Thinking escalation requires an exploit. Most real escalation is configuration: excessive rights already granted, a writable privileged path, or a stored credential.
  • Treating the initial breach as the whole incident. The breach is the start; escalation is what makes it serious, and blocking escalation is what contains it.
  • Confusing horizontal escalation with lateral movement. Horizontal escalation reaches another identity's resources at the same level; lateral movement reaches other machines.
  • Regarding least privilege as an inconvenience. It is the control that makes a breach survivable, and its cost is small against the alternative.
  • Letting administrators log in to ordinary workstations. It places administrative credentials on the machines most likely to be compromised.
  • Granting powerful rights without recognising them as escalation paths. The ability to install drivers, debug processes or manage services is effectively administrator.

Quick revision

  • System hacking is gaining access then increasing control; privilege escalation is the engine.
  • Vertical escalation raises the privilege level (the dangerous form); horizontal reaches another identity's resources at the same level; lateral movement spreads to other machines and is a different idea.
  • Routes: missing patches; weak permissions on privileged processes (a privileged process must not read or execute anything a lesser user can modify); excessive privileges already granted (so no escalation is needed); stored credentials in scripts and configuration; credential material in memory from other users' sessions; default credentials; and legitimate rights that confer escalation by design.
  • Only the first is a software flaw; the rest are defenders' decisions.
  • Defences: least privilege above all, separate administrative accounts that never log in to workstations, prompt patching, correct permissions, no stored secrets, application allow-listing, and monitoring for administrative actions, new accounts, changed group memberships and stopped security tools.

Test yourself

  1. Why is privilege escalation described as the pivotal step in a compromise?

Because a realistic initial foothold, such as a phished ordinary account or the rights of a web service, grants very little. Escalation converts it into control of the host, allowing the attacker to read everything, install software, disable defences, harvest credentials and move onward, so it is the step that distinguishes a contained incident from a serious breach.

  1. Distinguish vertical escalation, horizontal escalation and lateral movement.

Vertical escalation raises the attacker's privilege level on a system, for example from ordinary user to administrator. Horizontal escalation gains access to another principal's resources at the same privilege level, such as one user reading another's records. Lateral movement spreads to other machines across the network, typically using credentials or trust obtained from the first host.

  1. State the permissions rule that prevents a whole class of escalation, and explain it.

A privileged process must not read or execute anything that a lesser-privileged user can modify. If a service's program file, a scheduled task's script, or a configuration file consumed by a privileged process is writable by ordinary users, an attacker can substitute their own content and have it executed with high privilege without needing any software vulnerability.

munotes.in234

System Hacking and Privilege Escalation

  1. Why is it dangerous for administrators to log in to ordinary workstations?

Because authentication leaves credential material in the machine's memory, so an attacker who has compromised that workstation and obtained sufficient rights may recover the administrator's credentials or tokens. That converts the compromise of one ordinary workstation into compromise of the wider estate, which separate administrative accounts used only on managed administrative systems prevent.

  1. Why is least privilege the most important control in this chapter?

Because it does not attempt the impossible task of preventing every foothold, but ensures that a foothold lands somewhere with minimal rights and leaves a wall between the attacker and control. It therefore makes a breach survivable and contained, whereas an environment where ordinary users hold administrative rights requires no escalation at all.

Contents This chapter on its own page

munotes.in235

Chapter Forty-Nine

Escalation Routes on Linux and Windows, at Concept Level

Syllabus topic Module 1, "System Hacking and Privilege Escalation Concepts: Analyze ... privilege escalation techniques ... from a defensive perspective"

In one line

Both platforms provide legitimate mechanisms for running things with elevated privilege, and on both the escalation routes are the same idea in different clothes: a privileged mechanism that trusts something an ordinary user can change.

In examination wording: privilege escalation routes arise from the misconfiguration of platform mechanisms intended to delegate privilege, from unpatched local vulnerabilities, from credentials accessible to lesser-privileged users, and from the assignment of rights that confer administrative capability by design.

The one idea, stated first

Before either platform, the pattern that unifies everything below:

Something runs with high privilege. It depends on a file, a path, a setting or an account. If a low-privileged user can influence that dependency, they can influence what the privileged thing does.

Every route in this chapter is an instance. Learn the pattern and the specific routes become examples rather than a list, which is what lets a student reason about a system they have never administered.

Linux

The mechanisms that delegate privilege

The sudo mechanism lets named users run named commands as another user, normally root. It is the correct way to delegate administration, and its configuration is where mistakes are made.

The setuid bit is a permission that makes a program run as its owner rather than as the user who started it. It exists because some legitimate operations genuinely require privilege: changing your own password writes to a file only root may write. A setuid-root program is therefore privileged code that any user may start.

Capabilities divide root's powers into finer pieces, so a program can be given just the one privilege it needs rather than all of them. Used well they reduce risk; granted carelessly, a single powerful capability is equivalent to root.

Scheduled jobs run at intervals, often as root.

How each becomes a route

Over-broad sudo rules. The classic misconfiguration is permitting a user to run, as root, a program that can do more than the administrator intended. Many ordinary programs can read or write arbitrary files, or start another program; if such a program can be run as root, the user effectively has root. The administrator wanted to delegate one task and delegated the system.

The audit is to read the configuration and ask, for every entry, "what else can this program be made to do?" rather than "is this program dangerous?".

Writable setuid programs, or setuid programs that trust their environment. A setuid-root program that reads a configuration file a user can edit, or invokes another program by a relative path so the user can control which one is found, executes the user's choice as root. The general defect is a privileged program trusting input or environment it should validate.

munotes.in236

Escalation Routes on Linux and Windows, at Concept Level

The audit is to enumerate every setuid-root binary on the system and justify each one. The list should be short, should consist of well-known system programs, and anything unexpected, particularly anything an application installed, deserves scrutiny.

Excessive capabilities, where a binary has been granted a capability that permits reading any file, changing ownership, or loading kernel modules, any of which leads to root.

Writable paths used by root's scheduled jobs. If a job running as root executes a script in a directory an ordinary user can write to, the user replaces the script and waits. The same applies to any file the job reads and trusts.

World-writable files and directories generally, especially those in the path of anything privileged.

Group membership that confers privilege. Some groups grant, in effect, administrative capability: a group permitting container management, or direct disk access, or management of the virtualisation layer, can usually be turned into root. Adding a user to such a group is granting administration, and administrators often do not realise it.

Credentials in readable files. Scripts, deployment configuration, environment files and history files.

Unpatched local kernel or service vulnerabilities, the direct route.

The Linux audit, in one list

Enumerate setuid and setgid binaries; read the sudo configuration entry by entry and ask what each permitted program could be made to do; list capabilities granted to binaries; check ownership and permissions on everything privileged jobs read or execute; find world-writable files and directories; review membership of privilege-conferring groups; search for credentials in readable files; and confirm the kernel and packages are patched.

Windows

The mechanisms that delegate privilege

Services run in the background, frequently with high privilege, and start automatically.

Scheduled tasks run programs at times or on events, often with elevated rights.

Privileges assigned to accounts are named rights, distinct from group membership, that permit specific powerful operations.

User Account Control mediates elevation for interactive administrators.

How each becomes a route

Unquoted service paths. A service configured with a program path containing spaces, written without quotation marks, is ambiguous: the system may try several interpretations in order, and if a user can create a file at one of the earlier interpretations, it is executed with the service's privilege. This is a long-standing and still-common finding, and it is a pure configuration defect.

Weak permissions on service executables or their directories. If a user can replace the program a privileged service runs, they control that service. Likewise if they can modify the service's configuration to point elsewhere, or can restart it.

Weak permissions on scheduled tasks, exactly the same logic.

Always-install-elevated settings, a policy that causes installer packages to run with full privilege regardless of who starts them. Where enabled, any user can install anything as an administrator, and it exists only to work around badly written software.

munotes.in237

Escalation Routes on Linux and Windows, at Concept Level

Stored credentials: saved credentials in the operating system's store, passwords in unattended-installation files left behind after deployment, credentials in scripts and in task definitions, and passwords distributed by configuration management to every machine.

Credential material in memory. The route emphasised in the previous chapter: an attacker with administrative rights on a host can often recover credentials or tokens belonging to other sessions, which is why an administrator logging in to an ordinary workstation is dangerous, and why lateral movement so often follows one workstation compromise.

Privileges that are administrator in disguise. Rights permitting a user to debug arbitrary processes, load drivers, back up or restore any file regardless of its permissions, act as part of the operating system, or take ownership of objects, each amounts to administrative capability. Granting one is granting administration.

Group membership, similarly: groups that manage backups, print operators on older systems, or any group with rights over administrative objects.

Unpatched local vulnerabilities, again the direct route.

The Windows audit, in one list

Check every service for unquoted paths and for permissions on its executable, directory and configuration; check scheduled tasks the same way; confirm the always-install-elevated policy is disabled; search for credentials in unattended-installation files, scripts, task definitions and the credential store; review which accounts hold the powerful named privileges; review membership of privilege-conferring groups; ensure administrators do not log in to workstations; and confirm patching.

The two platforms side by side

The patternLinuxWindows
A privileged program a user can replaceWritable setuid binary; script run by a root jobService or scheduled-task executable with weak permissions
A privileged program that resolves a path looselyRelative path or environment trusted by setuid codeUnquoted service path
Delegation configured too broadlyOver-broad sudo rulesAlways-install-elevated; over-granted privileges
Fine-grained privilege granted carelesslyCapabilities on a binaryNamed privileges (debug, load driver, backup, take ownership)
Group membership equivalent to rootContainer, disk or virtualisation groupsBackup and other administrative-adjacent groups
Credentials left where a user can read themScripts, environment files, historyUnattended-install files, task definitions, credential store
Credentials recoverable from a live systemProcess memory, agent socketsMemory from other sessions, tokens
Unpatched local flawKernel or privileged serviceKernel or privileged service

Reading the table across each row is the point of the chapter: the mechanism differs, the mistake does not.

The defences, which are the same on both

  1. Least privilege, so the account the attacker lands on has little and so fewer things run privileged at all.
  2. Patch promptly, closing the direct routes.
  3. Correct permissions on everything privileged, which is the single most productive audit in this chapter and is entirely automatable. Nothing a privileged process depends on should be modifiable by a lesser user.
  4. Delegate narrowly. Grant the specific command or capability, not a program that can be turned to other purposes, and review each delegation by asking what else it permits.
  5. No stored secrets. Use a secret-management system; remove deployment artefacts after installation.
  6. Separate administrative accounts, never used on ordinary workstations.
  7. Application allow-listing, which blocks tools that do not belong.
  8. Monitor for new services and scheduled tasks, changes to privileged binaries, group and privilege changes, and access to credential stores.
munotes.in238

Escalation Routes on Linux and Windows, at Concept Level

A worked example

A tester reviews one Linux server and one Windows workstation with authorisation, and reports paths rather than exploits.

Linux server. Four findings: a sudo rule permitting a developer to run, as root, a text-processing program that can also write arbitrary files; a setuid binary installed by an application, which nobody can justify; a root scheduled job executing a script in a directory writable by the application group; and a deployment script, readable by all users, containing a database administrator's password.

Windows workstation. Three findings: a third-party service with an unquoted path whose earlier interpretations lie in a user-writable directory; a scheduled task whose script is writable by users; and a saved administrative credential in the credential store from a support visit.

The common recommendation is the same on both: enumerate everything that runs with privilege, and for each, verify that nothing it depends on can be modified by anyone with fewer rights than it runs with. Then remove the delegations and stored credentials that cannot be justified.

The tester demonstrated none of the escalations, because the misconfigurations are visible by inspection and the finding is the misconfiguration, not a demonstration of it. That is the defensive register of the chapter in practice.

What beginners get wrong

  • Treating the routes as a memorised list. They are one pattern: a privileged mechanism trusting something a lesser user controls.
  • Assuming escalation needs a vulnerability. Most of this chapter is configuration, findable by inspection.
  • Reviewing sudo rules by asking whether the program is dangerous. The right question is what else the program can be made to do, since many ordinary programs can write files or start others.
  • Overlooking unquoted service paths. A pure configuration defect, long-standing and still commonly found.
  • Granting powerful named privileges or group memberships without recognising them as administrator. Debugging processes, loading drivers, backing up any file and taking ownership all confer administrative capability.
  • Leaving deployment artefacts on disk. Unattended-installation files and provisioning scripts routinely contain credentials.
  • Permitting administrators to log in to workstations, which places their credentials on the machines most likely to be compromised.
munotes.in239

Escalation Routes on Linux and Windows, at Concept Level

Quick revision

  • The pattern: a privileged mechanism that trusts something a lesser user can change.
  • Linux mechanisms: sudo, setuid, capabilities, root scheduled jobs. Routes: over-broad sudo rules, writable or environment-trusting setuid binaries, excessive capabilities, writable paths used by root jobs, privilege-conferring group membership, readable credentials, unpatched flaws.
  • Windows mechanisms: services, scheduled tasks, named privileges, User Account Control. Routes: unquoted service paths, weak permissions on service and task executables, always-install-elevated, stored credentials in unattended-install files and the credential store, credential material in memory from other sessions, and privileges such as debug, load driver, backup and take ownership.
  • Audit both by enumerating everything privileged and checking that nothing it depends on is modifiable by a lesser user.
  • Defences on both: least privilege, patching, correct permissions on privileged dependencies, narrow delegation, no stored secrets, separate administrative accounts, allow-listing, and monitoring for new services, tasks, and privilege changes.

Test yourself

  1. State the single pattern underlying nearly all privilege-escalation routes, and give one example from each platform.

Something runs with high privilege and depends on a file, path, setting or account that a lesser-privileged user can influence, so the user influences what the privileged thing does. On Linux, a root scheduled job executing a script in a user-writable directory; on Windows, a service whose executable or configuration has permissions allowing users to replace it.

  1. What is an unquoted service path and why does it permit escalation?

A Windows service configured with a program path containing spaces but no quotation marks, which the system may interpret in several ways in order. If a user can create a file matching one of the earlier interpretations, that file is executed with the service's privilege at start-up. It is a pure configuration defect requiring no vulnerability.

  1. Why is auditing sudo rules by asking "is this program dangerous?" the wrong question?

Because many ordinary, apparently harmless programs can write arbitrary files, read protected files, or start another program. The correct question is what else the permitted program could be made to do when run as root, since the administrator's intention to delegate one narrow task does not constrain the program's capabilities.

  1. Name three Windows privileges or group memberships that amount to administrative capability, and say why granting them matters.

The rights to debug arbitrary processes, to load drivers, to back up or restore any file regardless of permissions, or to take ownership of objects; and membership of groups with rights over administrative objects. Each can be converted into full administrative control, so granting one is granting administration even though it appears to be a narrow permission.

  1. What is the single most productive audit described in this chapter?
munotes.in240

Escalation Routes on Linux and Windows, at Concept Level

Enumerating everything that runs with elevated privilege, services, scheduled tasks, setuid binaries, capability-holding binaries and privileged jobs, and verifying for each that no file, directory, path or configuration it depends on can be modified by any user with fewer rights than it runs with. It is automatable and it closes an entire class of route.

Contents This chapter on its own page

munotes.in241

Chapter Fifty

Detecting Persistence: the Auto-Start Audit

Syllabus topic Module 1, "System Hacking and Privilege Escalation Concepts"; the fourth phase of the lifecycle, read defensively

In one line

For anything to run automatically after a restart, the system must record where to find it, in a finite and well-known set of start-up locations. That is the defender's opportunity: those locations can be enumerated, compared against a known-good baseline, and monitored, so persistence is the phase most amenable to detection.

In examination wording: maintaining access is the lifecycle phase in which continued availability of a compromised system is sought; from a defensive standpoint it is significant because the mechanisms that cause code to execute automatically are finite, enumerable and recorded in the system's own configuration, and therefore detectable by baselining and monitoring those mechanisms.

Why this phase favours the defender

Most of this book has shown attacks with an advantage: reconnaissance is invisible, a phish needs one success, a scan hides in background noise. This phase is different, and it is worth dwelling on the reversal, because it is where a defender is strongest.

The reason is structural. A system runs code at start-up, at login, and on a schedule only if it has been told where that code is. There is no way to have something run automatically without a durable record of it somewhere the operating system reads. Those records live in a bounded set of locations that are the same on every machine of a given type, are documented, and are exactly what legitimate software also uses.

So the defender does not have to guess. They can list every one of those locations, ask what is in it, and compare that against what should be there. Anything present that is not accounted for is a finding. This is the discipline the tool commonly called an auto-runs inspector automates, and it is the core of host-based incident response.

The lesson to carry: persistence is a recorded, enumerable state, not a hidden action. That is why the phase belongs to the defender, and why an organisation that baselines and monitors its start-up configuration turns an intruder's need to survive a reboot into the intruder's most reliable point of discovery.

The known-good baseline

Detection here rests on one idea: you can only recognise the abnormal if you have recorded the normal.

A baseline is a record, captured when a system is known to be clean, of what should be present in each start-up location, together with the cryptographic hashes of the important files. It is captured at build time, from the standard image, before the machine is exposed to anything, and it is stored off the machine, so that a later comparison does not depend on the machine's own honesty.

With a baseline, the audit becomes a comparison rather than a judgement: this scheduled task is not in the baseline; this start-up entry points to a file whose hash does not match; this service was not on the standard image. Without a baseline, the same audit is a matter of an analyst recognising names, which is slow, error-prone, and defeated by anything named to look ordinary.

munotes.in242

Detecting Persistence: the Auto-Start Audit

The baseline is also what makes change visible over time. Most persistence, legitimate or otherwise, appears as a change to a location that was previously stable, so recording the locations and alerting on changes to them is the single most effective control in this chapter.

The categories of start-up mechanism

A defender audits categories rather than memorising every entry, because the categories are stable across systems even as the specifics differ. At concept level, code is made to run automatically through:

  • Boot and service mechanisms: the components the system starts as it comes up, and the background services it launches. Both platforms have a managed list of these, and both record, for each, the program to run.
  • Login and session mechanisms: things that run when a user logs in, from per-user start-up entries to session initialisation scripts.
  • Scheduled mechanisms: tasks configured to run at times or on events such as a user logging in or a device connecting.
  • Extension and plug-in mechanisms: places where a legitimate program loads additional code, such as browser extensions, and libraries loaded by other programs.
  • Configuration that redirects execution: settings that cause a trusted program to load a different file than expected, which is the escalation pattern from the previous chapter appearing as a persistence route.

The defensive point is that every one of these is also where legitimate software lives, which is why detection needs a baseline: the location alone does not distinguish good from bad, only the comparison does.

What the audit looks for

Working from the baseline, the audit asks a small number of questions of each location, and each maps to a well-understood indicator:

  • Is anything present that is not in the baseline? A new service, task or start-up entry that no change record explains.
  • Does anything point to a file whose hash has changed without a corresponding update? A baselined entry now referring to a modified program.
  • Does anything point to an unusual place? A start-up entry referring to a user's temporary or downloads area rather than a program directory is inherently suspicious, because legitimate software installs to program directories.
  • Is anything named to resemble a legitimate component but located wrongly, or spelled slightly differently from a real system file? Masquerading by name is common, and the baseline defeats it because the real component's location and hash are known.
  • Was anything created at an unexpected time, for example a start-up entry whose timestamp coincides with a suspected intrusion rather than with a software installation?
munotes.in243

Detecting Persistence: the Auto-Start Audit

None of these requires knowing how the entry was placed. Each is a property of the recorded state, which is why the audit is a defensive activity and not a reconstruction of an attack.

Integrity monitoring and continuous detection

The one-off audit is valuable; making it continuous is better, and the mechanism is file integrity monitoring together with configuration monitoring.

Integrity monitoring keeps hashes of the important files and of the start-up configuration and re-checks them, raising an alert when one changes without an authorised reason. It is the same idea as the baseline applied continuously, and it is the control that catches the change at the moment it happens rather than at the next manual review.

Two design requirements make it trustworthy, and both echo earlier chapters:

  • The records must live off the host, because a record kept on the machine is only as trustworthy as the machine, which is the very thing under question. This is the same argument the covering-tracks chapter makes about logs.
  • The monitoring must account for legitimate change. Systems change constantly through patching and updates, so the monitoring must be tied to the change process: an authorised update explains a changed hash, and an unexplained change is the alert. Monitoring that cannot distinguish the two produces noise and is switched off, which is the base-rate problem from the intrusion-detection chapter in another form.

Endpoint detection and response tools combine this with behavioural monitoring, watching for the creation of start-up entries and scheduled tasks as events, which is why they are the modern instrument for this phase.

Removal, and why it is not the whole answer

When the audit finds an unaccounted-for persistence entry, removing it is necessary and not sufficient, and the reason connects to the next two chapters.

Necessary: the entry is removed and the file it points to is preserved for analysis, not simply deleted, because it is evidence.

Not sufficient, for two reasons. First, persistence is usually multiple: an intruder who has established one mechanism has frequently established others, precisely so that removing one does not end their access, so finding one is a reason to search harder rather than to relax. Second, and more important, the presence of unaccounted-for persistence means the system was compromised, and the safe response to a confirmed compromise of any depth is not to clean individual artefacts but to rebuild from known-good media and restore data from clean backups, for the reason the rootkit chapter gives in full: a system that has been controlled by an intruder cannot be trusted to report its own state truthfully.

munotes.in244

Detecting Persistence: the Auto-Start Audit

So the audit's output is not "delete this entry" but "this host is compromised; contain it, preserve evidence, hunt for the other mechanisms, and rebuild it." That is the honest defensive conclusion, and it is why detection matters more than any single removal.

The tester's discipline

Because this is the "maintaining access" phase, a word on what an ethical tester does, which is the mirror of everything above.

A tester demonstrates persistence only where the scope explicitly permits it, because installing anything that survives a reboot on a client's system is exactly the kind of change the rules of engagement govern. When they do, they record precisely what was placed and where, and they remove it at the end, verifying the removal against the same audit a defender would run. The purpose is to show the client that persistence would have been possible and that their monitoring did or did not detect it, not to leave a foothold behind. An engagement that ends with an undocumented persistence mechanism still on a client's estate is a serious professional failure, which is why the clean-up and its verification are part of the deliverable.

A worked example, run as a defender

A monitoring alert indicates that a start-up configuration on a workstation changed outside the patch window. An analyst runs the audit.

  • They compare the machine's start-up locations against the baseline captured from the standard image. One scheduled task and one service are present that the baseline does not contain and that no change record explains.
  • The service points to a program in a user temporary directory rather than a program directory, which is inherently wrong for a service.
  • The file's creation time coincides with a suspicious login flagged earlier in the week, not with any installation.
  • Because one unaccounted-for mechanism is present, the analyst searches the remaining categories and finds a login-time entry as well, confirming that removing the first alone would not have ended the access.

The response is not to delete the three entries and move on. It is to isolate the host from the network, preserve the files and the configuration as evidence, treat the machine as compromised and therefore untrustworthy, rebuild it from clean media and restore its data from backups predating the intrusion, and then ask the question that matters most: how did the intruder get the access to place these, and what else did they reach, since a workstation compromise is rarely the whole story.

The audit found the persistence; the persistence proved the compromise; the compromise triggered the response. That chain is the chapter, and every link in it is defensive.

munotes.in245

Detecting Persistence: the Auto-Start Audit

What beginners get wrong

  • Thinking persistence is hidden action rather than recorded state. It is a durable entry in a known location, which is exactly why it is findable.
  • Auditing without a baseline. Recognising bad names by eye is slow and defeated by ordinary-looking names; comparison against a known-good record is what works.
  • Keeping the baseline and the integrity records on the host. A record on the machine is only as trustworthy as the machine, which is the thing in question. Store them off-host.
  • Removing one mechanism and stopping. Persistence is usually multiple; finding one is a reason to search harder.
  • Cleaning instead of rebuilding. Unaccounted-for persistence proves compromise, and a compromised system cannot be trusted to report its own state; the safe answer is to rebuild from clean media.
  • Ignoring the upstream question. The persistence is the symptom; how the access was obtained, and what else was reached, is the investigation.
  • A tester leaving persistence behind. It is exercised only within scope, recorded, and removed with the removal verified.

Quick revision

  • Anything that runs automatically must be recorded where the system reads it, in a finite, documented set of start-up locations, so persistence is enumerable state, not hidden action, and the phase favours the defender.
  • Detection rests on a known-good baseline: what should be in each location and the hashes of the important files, captured clean at build time and stored off the host.
  • Categories to audit: boot and service mechanisms, login and session mechanisms, scheduled mechanisms, extension and plug-in mechanisms, and configuration that redirects execution. Every category also holds legitimate software, so the comparison, not the location, is what distinguishes.
  • The audit asks: is anything present that is not baselined; does anything point to a changed hash or an unusual location; is anything masquerading by name; was anything created at a suspicious time.
  • File integrity and configuration monitoring make the audit continuous; records off-host, tied to the change process so authorised updates are not false alarms.
  • Removal is necessary and not sufficient: persistence is usually multiple, and unaccounted-for persistence proves compromise, so the safe response is rebuild from clean media, plus investigate how the access was obtained.
  • A tester tests persistence only within scope, records it, and removes it, verifying removal.

Test yourself

  1. Why is the maintaining-access phase the one most favourable to the defender?

Because anything that runs automatically after a restart must be recorded in a durable, documented and finite set of start-up locations that the operating system reads. Persistence is therefore an enumerable state rather than a hidden action, so a defender can list every such location, compare it against a known-good baseline, and monitor it for change, turning the intruder's need to survive a reboot into a reliable point of detection.

munotes.in246

Detecting Persistence: the Auto-Start Audit

  1. What is a known-good baseline, and why must it be stored off the host?

It is a record, captured from a clean standard image at build time, of what should be present in each start-up location together with the hashes of the important files. It must be stored off the host because a comparison depends on the record being trustworthy, and a record kept on a possibly compromised machine is only as trustworthy as that machine, which is the very thing in question.

  1. Why does the location of a start-up entry not, by itself, tell you whether it is malicious?

Because every start-up mechanism is also where legitimate software registers itself, so presence in such a location is normal. Only comparison against the baseline, or an indicator such as a changed hash, an unusual target path, a name masquerading as a system component, or a creation time coinciding with a suspected intrusion, distinguishes an unaccounted-for entry from a legitimate one.

  1. Why is removing a discovered persistence entry necessary but not sufficient?

Because persistence is usually established in more than one place, so removing a single mechanism does not end the access and finding one is a reason to search the other categories. More fundamentally, the presence of unaccounted-for persistence proves the system was compromised, and a compromised system cannot be trusted to report its own state, so the safe response is to preserve evidence, rebuild from known-good media, restore clean data, and investigate how the access was obtained and what else was reached.

  1. What discipline must an ethical tester observe with respect to persistence?

It may be exercised only where the engagement's scope explicitly permits it, because installing anything that survives a reboot is a change the rules of engagement govern. The tester records exactly what was placed and where, removes it at the end, and verifies the removal against the same audit a defender would run, so that the engagement demonstrates the risk and its detectability without leaving any foothold on the client's estate.

Contents This chapter on its own page

munotes.in247

Chapter Fifty-One

Covering Tracks, and Why a Defender Protects the Logs

Syllabus topic Module 1, "System Hacking and Privilege Escalation Concepts"; the fifth phase of the lifecycle, read defensively

In one line

The logs are the record of the attack, so they are the thing an intruder has most reason to alter and a defender has most reason to protect. The whole of this phase, for a defender, is a single design goal: make the record trustworthy even after the system that produced it is compromised.

In examination wording: covering tracks is the final lifecycle phase, in which an intruder seeks to remain undetected; from a defensive standpoint its significance is that audit logs are the primary evidence of intrusion, so their integrity and availability must be assured independently of the hosts that generate them, principally by forwarding them to a separate, append-only, access-controlled system.

Why the logs are the target

Everything the earlier phases did leaves a trace: a login, a new service, a scheduled task, a connection to an unfamiliar address, a privilege change, a file access. Those traces are the logs, and collectively they are the story of the intrusion. An intruder who wants to remain undetected has one obvious interest, which is that the story not be readable.

So the design question for a defender is not "how does an intruder tamper with logs?" but its complement: given that whoever controls a machine can alter anything stored on that machine, how do we keep a record they cannot alter? That question has a clean answer, and it is the chapter.

The answer generalises the single most important principle in host-based defence, already met twice in this book: never let a system be the sole witness to its own compromise. The persistence chapter said the baseline must live off the host; the rootkit chapter will say integrity must be checked from outside the host; here it is the logs. The same idea each time.

The one control: get the logs off the host, immediately

The decisive measure is to forward every log entry to a separate collection system as it is produced, so that within moments of an event being recorded a copy exists on a machine the origin host cannot write to.

Why this works is worth stating precisely, because it is the whole argument. An intruder who compromises a host can alter the logs on that host. They cannot alter a copy that has already left it and sits on a system they do not control. So the window in which the local log is the only copy is the window in which tampering matters, and forwarding immediately shrinks that window to near zero. Anything that happened before the intruder gained control has already been copied away; anything they do after is recorded and copied away as it happens.

Three properties make the central collector trustworthy:

munotes.in248

Covering Tracks, and Why a Defender Protects the Logs

  • Separation. The collector is a different system, administered separately, reachable by the hosts only to send logs, never to modify what has been sent. Compromising a host does not confer any access to the collector.
  • Append-only. The collector accepts new entries and does not permit existing ones to be altered or deleted, so even an account on the collector cannot rewrite history. Write-once storage enforces this at the medium.
  • Access control and monitoring on the collector itself. It is a high-value target, since it holds the evidence for the whole estate, so it is hardened, tightly restricted, and its own access is logged.

With those in place, the intruder's interest in the logs is largely defeated, not because they cannot touch the local copy but because the copy that matters is already elsewhere.

Detecting the attempt, which is a high-quality signal

A second defensive gain follows, and it is one of the best signals in this book.

Because clearing or stopping logging is rare in normal operation, the act itself is an excellent indicator. A legitimate administrator almost never clears an audit log; a service almost never stops logging without a reason. So a defender configures alerts on exactly those events:

  • the audit log being cleared;
  • logging being stopped or reconfigured;
  • a gap in a log stream that should be continuous, which the central collector can detect because it sees the stream from every host and notices when one goes quiet;
  • the logging configuration being changed.

These alerts have the property the intrusion-detection chapter prized: they are rare, so they carry little false-positive burden, and they fire precisely when something is trying to reduce visibility. An intruder who alters the local logs to hide their earlier activity thereby generates a fresh, loud, off-host alert about the alteration itself, which is the tampering turned against the tamperer.

For this to work, two supporting conditions matter:

  • Time must be synchronised across all hosts and the collector, which is why the enumeration chapter treated accurate time as a security requirement: entries from different machines can only be correlated into one timeline if their clocks agree, and a gap can only be recognised if the timeline is coherent.
  • The logs must actually contain the events that matter. Logging that records too little is defeated without any tampering, so the audit policy must capture logins, privilege use, account and group changes, service and task creation, and access to sensitive resources. A record that never existed cannot be protected.

What to log, briefly

Protecting logs is worthless if the logs are empty of the relevant events, so a defender ensures the audit policy captures the events the earlier phases produce: authentication successes and failures, use of elevated privilege, creation and modification of accounts and groups, creation of services and scheduled tasks (the persistence chapter's artefacts), changes to security settings, and access to sensitive data. The aim is that each phase of the lifecycle leaves an entry that reaches the collector, so the story remains readable end to end.

munotes.in249

Covering Tracks, and Why a Defender Protects the Logs

Over-logging has its own cost, in volume and in the base-rate problem, so the policy is a deliberate selection of security-relevant events rather than everything, and the selection is reviewed as the estate changes.

The tester's inversion

The lifecycle chapter set this out and it is repeated because it is the ethical heart of the phase. An intruder's fifth phase is concealment. An ethical tester does the opposite. They do not clear the client's logs. They may, where the scope permits, test whether logging can be evaded or whether an alert fires, because "our monitoring did not record this" or "clearing the audit log raised no alarm" is a valuable finding. But they preserve the client's evidence, they record precisely what they did and when, and they supply their source addresses in advance so the client can separate the test from any real activity, which is the deconfliction item from the rules-of-engagement chapter earning its place a second time.

The result is that an engagement ends with a fuller record than it began with, not an emptier one, and the client can reconstruct exactly what the tester touched. A tester who left the client unable to distinguish the test from an attack would have failed at precisely the thing this phase is about.

A worked example, read as a defender

A security team is assessing whether it could reconstruct an intrusion after the fact, so it runs an exercise, with authorisation, in which a tester performs a sequence of actions on a host and then attempts, within scope, to reduce the local record of them.

  • The host forwards its logs to a central collector as events occur, so the tester's earlier actions are already copied away before any attempt to alter the local logs.
  • When the local audit log is cleared, the collector both already holds the entries that were removed and raises an alert on the clearing event itself, which reached it before the local log was touched.
  • The collector notices a gap: for ninety seconds the host sent nothing, which its continuous view across all hosts makes visible.
  • Because time is synchronised, the team assembles a single timeline from the collector's copies and reconstructs the whole sequence, including the attempt to hide it.

The findings are a mix of positive and negative, which is the useful outcome. Positive: forwarding worked, the evidence survived, and the clearing raised an alert. Negative, had any been present: a host that did not forward, a collector that permitted deletion, or an audit policy that never recorded the privilege change in the first place. Each negative is a specific, fixable gap, and each maps to one of the properties above.

munotes.in250

Covering Tracks, and Why a Defender Protects the Logs

The exercise proves the chapter's claim: with the record off the host, the intruder's interest in the logs is defeated, and the attempt to act on that interest becomes one of the clearest alerts the organisation has.

What beginners get wrong

  • Leaving logs only on the host that produced them. A local log is only as trustworthy as the machine, which is the thing under investigation. The record that matters must already be elsewhere.
  • Thinking the goal is to prevent an intruder touching the local copy. It is not achievable and it is not the point; the point is that the copy that matters has already left. Forwarding immediately, not locking the local file, is the control.
  • Forgetting to alert on log clearing and logging stoppage. These are rare, high-quality signals, and an intruder acting on the logs generates them.
  • Neglecting time synchronisation. Without it, entries from different hosts cannot be correlated and gaps cannot be recognised.
  • Protecting logs that are empty of the relevant events. If the audit policy never recorded the privilege change or the new service, there is nothing to protect; capture the security-relevant events first.
  • A tester clearing the client's logs. The ethical inversion: preserve and document, test whether evasion is possible and whether it alerts, and leave the record fuller, not emptier.

Quick revision

  • The logs are the record of the attack, so they are what an intruder most wants altered and what a defender most needs protected.
  • The design goal: a record that stays trustworthy even after the host is compromised, from the principle never let a system be the sole witness to its own compromise.
  • The decisive control: forward every entry to a separate collector as it is produced, so a copy exists off-host within moments. The collector is separate, append-only, and hardened with its own access logged.
  • Tampering is defeated not by locking the local copy but because the copy that matters has already left the host.
  • Clearing logs, stopping logging, a gap in a continuous stream, and configuration changes are rare, high-quality alerts; an intruder acting on the logs triggers them. This needs synchronised time and an audit policy that actually captures the security-relevant events.
  • The tester's inversion: preserve the client's evidence, document their own activity, deconflict by supplying source addresses, and test whether evasion is possible and whether it alerts, leaving the record fuller.
munotes.in251

Covering Tracks, and Why a Defender Protects the Logs

Test yourself

  1. What is the single most important control for ensuring logs remain trustworthy after a compromise, and why does it work?

Forwarding every log entry to a separate collection system as it is produced. It works because whoever controls a host can alter anything stored on that host but cannot alter a copy that has already left it; forwarding immediately shrinks the window in which the local log is the only copy to near zero, so the evidence that matters is already beyond the intruder's reach.

  1. What three properties must the central log collector have?

Separation, so that compromising a host grants no access to the collector; append-only storage, so that existing entries cannot be altered or deleted even by an account on the collector; and its own hardening, access control and monitoring, because it holds the evidence for the whole estate and is therefore a high-value target.

  1. Why is clearing an audit log a valuable detection signal, and what must be in place for it to work?

Because clearing logs, stopping logging or a gap in a continuous stream are rare in normal operation, so they carry little false-positive burden and fire precisely when something is trying to reduce visibility; an intruder who alters the logs thereby generates a fresh off-host alert about the alteration. It requires synchronised time so events can be correlated and gaps recognised, and an audit policy that captures the relevant events in the first place.

  1. Why is protecting the logs pointless if the audit policy is inadequate, and what should it capture?

Because a record that was never created cannot be protected, so tampering is unnecessary to defeat it. The audit policy should capture the events the lifecycle phases produce: authentication successes and failures, use of elevated privilege, creation and modification of accounts and groups, creation of services and scheduled tasks, changes to security settings, and access to sensitive data.

  1. How does an ethical tester's handling of this phase differ from an intruder's?

An intruder conceals their activity by altering or deleting the record. An ethical tester preserves the client's evidence, documents exactly what they did and when, and supplies their source addresses so the client can distinguish the test from real activity; they may test whether evasion is possible and whether it raises an alert, but they leave the record fuller rather than emptier, so the engagement never leaves the client unable to reconstruct events.

Contents This chapter on its own page

munotes.in252

Chapter Fifty-Two

Rootkits: How They Hide and How They Are Found

Syllabus topic Module 1, "System Hacking and Privilege Escalation Concepts: Analyze ... rootkits ... from a defensive perspective"

In one line

A rootkit is malicious software whose purpose is to hide, by making the operating system lie to you about what is running, what files exist and what connections are open. Because it corrupts the system's own reporting, the only trustworthy way to find it is to look from outside that reporting.

In examination wording: a rootkit is software designed to conceal the presence of an intrusion by subverting the mechanisms a system uses to report on itself, so that malicious files, processes, connections or accounts do not appear through normal means; detection therefore relies on comparison against trusted external references rather than on the compromised system's own account of itself.

Why hiding is the whole point

Most malware wants to do something visible: encrypt files, send messages, mine currency, exfiltrate data. A rootkit's goal is different and it is the reason it is dangerous out of proportion to its own actions: it exists to make everything else invisible.

It sits in the maintaining-access phase and its job is to ensure that the foothold, the persistence, the other malware and the connections all go unseen, so that the intrusion continues. An intrusion you cannot see is one you cannot respond to, so a rootkit multiplies the harm of everything it conceals. That is why it is studied separately from the malware that does the damage: it is the malware that protects the damage.

The one idea: corrupting the source of truth

Everything about detecting a rootkit follows from a single observation, so the chapter states it once and builds on it.

When you ask a system a question, "what processes are running?", "what files are in this folder?", "what is listening on the network?", the answer comes from the system itself. A rootkit inserts itself between your question and the truth and edits the answer to remove any trace of the intrusion. The tool you would naturally use to look is the very thing that has been corrupted, so it reports that everything is normal.

How deeply the corruption sits determines how hard it is to catch, and a defender should know the three levels because they decide which detection methods can still be trusted:

  • A user-level rootkit tampers with ordinary programs and shared libraries, so the standard tools give doctored answers. Detectable by tools that do not rely on those libraries.
  • A kernel-level rootkit tampers with the operating system's core, so even the system's own accounting of itself is false. Much harder to catch from the running system, because the layer you would trust has itself been subverted.
  • A firmware or boot rootkit sits below the operating system entirely and loads before it, so it can survive even a reinstallation of the operating system.
munotes.in253

Rootkits: How They Hide and How They Are Found

The common thread, and the only thing a student really needs to carry: a rootkit corrupts the source of truth, so detection cannot rely on that source.

Detection: look from outside the lie

Because the running system's account of itself is untrustworthy, every reliable detection method works by comparing against something the rootkit does not control. Four approaches, in increasing independence from the compromised system:

Integrity monitoring against a trusted baseline. The same baseline idea from the persistence chapter: hashes of the important files, recorded when the system was clean and stored off the host, re-checked later. A file that has changed without an authorised reason is a flag, and because the baseline lives elsewhere the rootkit cannot make the changed file match it.

Cross-view comparison. Ask the same question two different ways and compare. A rootkit typically hides through one interface but cannot doctor every possible route to the same information, so a discrepancy between a high-level answer and a low-level one, between what the system reports and what a raw enumeration finds, reveals the concealment. The tell is the mismatch, not either answer alone.

Behavioural and external evidence. A rootkit can hide a file or a process, but it is far harder to hide effects that are observed from elsewhere. Unexpected network connections seen by a separate device on the network, a machine that is busier than its visible processes explain, or traffic to an unfamiliar address in the off-host logs, are all visible without asking the compromised system anything.

Examination from clean media. The most decisive method: boot the suspect machine from a known-clean external system, or attach its disk to a trusted analysis machine, and examine it while the rootkit is not running. It cannot lie about what it cannot execute, so the files and entries it hid from the live system become visible. This is the reference against which the live system's account can finally be checked.

The principle behind all four is the block's principle, now at its sharpest: never ask a possibly compromised system to certify its own health; check it against a record, a second view, an external observer, or a clean examination it does not control.

Why antivirus alone is not enough here

A student reasonably asks why an anti-malware product does not simply catch it. Two reasons, and both are important.

First, a rootkit deep enough to subvert the kernel can hide from a scanner that is running on the same system, because the scanner asks the operating system the same questions everything else does and receives the same doctored answers. A scanner is most effective against a rootkit when it runs from outside, for example from clean boot media.

munotes.in254

Rootkits: How They Hide and How They Are Found

Second, signature detection finds known rootkits, and the ones that matter most are often tailored and unknown. So the layered methods above, integrity, cross-view, external evidence and clean examination, are what catch the novel case, exactly as the malware-detection chapter will argue for malware in general.

Remedy: for a confirmed deep rootkit, rebuild

The honest defensive conclusion, and it is a hard message a defender must be able to deliver plainly.

Once a kernel or firmware rootkit is confirmed, the only trustworthy remedy is to rebuild the machine from known-clean media: wipe and reinstall the operating system from a trusted source, restore data from backups that predate the intrusion, and, for a firmware-level infection, follow the vendor's firmware-recovery process, because a plain operating-system reinstall does not reach firmware.

Attempting to clean a deep rootkit in place is unreliable, because doing so means trusting a system that has already demonstrated it will lie about its own state. You would be asking the corrupted source of truth to confirm it has been repaired. For a user-level rootkit the situation is less severe, but the safe default for any confirmed rootkit is to treat the host as untrustworthy and rebuild, which is the same conclusion the persistence chapter reached and for the same reason.

A rebuild is unwelcome to a user who wants their machine back today, and stating it clearly, with the reason, is part of the defender's job.

A worked example, run as a defender

A workstation is slow, and from the network side, using a separate device, it is seen making connections at night to an unfamiliar address, although the machine's own task list shows nothing unusual.

  • The discrepancy is the classic indicator: network activity that the host's own view does not explain. The defender does not trust the host's tools, because a rootkit's purpose is to make exactly those tools lie.
  • They perform a cross-view comparison and find that a low-level enumeration lists a process the standard view omits, confirming concealment.
  • They boot the machine from clean media and examine the disk with the rootkit not running; a hidden driver and hidden files appear that the live system had concealed.
  • Checking the off-host integrity records, the changed system file would have been flagged when it was first altered had continuous monitoring been in place; the report recommends deploying it.

Because a kernel driver was involved, the remedy is not to delete the file and hope, but to treat the machine as compromised and untrustworthy, rebuild it from clean media, restore its data from backups predating the change, and investigate how the access to install it was obtained. Every step relies on evidence gathered from outside the compromised system, which is the chapter in practice.

munotes.in255

Rootkits: How They Hide and How They Are Found

What beginners get wrong

  • Trusting the infected system's own tools. A rootkit's entire purpose is to make those tools lie; detection must come from outside the system's control.
  • Believing antivirus running on the host catches everything. A deep rootkit hides from an on-host scanner; scanning from clean media, and the layered methods, catch what it misses.
  • Thinking a deep rootkit can be cleaned in place. For a kernel or firmware rootkit the safe remedy is rebuild from clean media, because cleaning trusts a system that has shown it will lie.
  • Forgetting firmware persistence. A firmware or boot rootkit survives an operating-system reinstall; firmware recovery is a separate step.
  • Looking only at the host. The best early indicators, unexpected connections and unexplained load, come from outside: a network view and off-host logs.
  • Stopping at removal. A rootkit proves a compromise; how the access was obtained, and what else it protected, is the investigation.

Quick revision

  • A rootkit hides an intrusion by corrupting the system's own reporting, so malicious files, processes, connections and accounts do not appear. It protects the damage rather than doing it.
  • Levels: user (tampered programs and libraries), kernel (the core is subverted), firmware or boot (below the operating system, survives reinstallation). Deeper means harder to detect from the running system.
  • The one idea: it corrupts the source of truth, so detection cannot rely on that source.
  • Detection from outside the lie: integrity monitoring against an off-host baseline; cross-view comparison (a discrepancy between two ways of asking); behavioural and external evidence (unexpected connections and load seen off-host); and examination from clean media (the rootkit not running cannot lie).
  • On-host antivirus is defeated by a deep rootkit; scan from clean media and use the layered methods.
  • Remedy for a confirmed kernel or firmware rootkit: rebuild from clean media, restore clean backups, recover firmware separately; cleaning in place trusts a system that has shown it will lie.

Test yourself

  1. What distinguishes a rootkit from other malware, and why is that so dangerous?

Its purpose is to hide rather than to act, by corrupting the mechanisms a system uses to report on itself so that intrusions do not appear. It is dangerous out of proportion to its own actions because it conceals everything else, the foothold, the persistence, the other malware, and an intrusion that cannot be seen cannot be responded to.

  1. Why can a rootkit not be reliably detected using the infected system's own tools?

Because it inserts itself between a question and the truth and edits the answer, and the standard tools obtain their answers from the very mechanisms it has corrupted. A kernel-level rootkit subverts the operating system's own accounting, so even the system's built-in reporting, and an on-host scanner that relies on it, receive the doctored answers.

munotes.in256

Rootkits: How They Hide and How They Are Found

  1. Name the four detection approaches that work from outside the compromised system's reporting.

Integrity monitoring against a trusted baseline stored off the host; cross-view comparison, in which the same question asked two different ways reveals a discrepancy the rootkit cannot doctor everywhere; behavioural and external evidence, such as unexpected connections or unexplained load observed from the network and off-host logs; and examination from clean media, booting or attaching the disk so the rootkit is not running and cannot conceal anything.

  1. Why is rebuilding from clean media the safe remedy for a confirmed kernel or firmware rootkit?

Because cleaning it in place requires trusting a system that has already demonstrated it will lie about its own state, so any confirmation of repair comes from the corrupted source itself. Rebuilding from known-clean media and restoring data from backups predating the intrusion re-establishes a trustworthy system, and firmware-level infection additionally requires the vendor's firmware-recovery process because an operating-system reinstall does not reach firmware.

  1. What single principle unifies persistence detection, log protection and rootkit detection?

Never let a system be the sole witness to its own state or compromise. Persistence detection needs an off-host baseline, log protection needs an off-host append-only collector, and rootkit detection needs comparison against an external reference, because a system an intruder controls cannot be trusted to report truthfully about itself.

Contents This chapter on its own page

munotes.in257

Chapter Fifty-Three

Spyware and Keyloggers from the Defensive Side

Syllabus topic Module 1, "System Hacking and Privilege Escalation Concepts: Analyze ... spyware technologies from a defensive perspective"

In one line

Spyware secretly collects information and sends it to someone else; a keylogger is the specific form that records what is typed. Both are detected the same way as any covert program: by the traces their necessary parts leave, and prevented by the same endpoint discipline that limits all malware.

In examination wording: spyware is software that covertly gathers information about a user or system and transmits it to a third party; a keylogger is spyware that records keystrokes to capture credentials, messages and other typed data; both are countered by endpoint protection, least privilege, control over what may be installed and connected, and monitoring for the collection, persistence and exfiltration behaviours they must exhibit.

Why they are studied with rootkits

Spyware shares the rootkit's instinct to stay quiet, but its goal is collection rather than concealment of a foothold. Where a rootkit hides an intrusion, spyware harvests: passwords, banking details, messages, documents, browsing, and, in the keylogger's case, every keystroke including the ones typed into a password box before any masking.

They are placed together because they are the covert half of the malware world, the programs whose success depends on not being noticed, and so they are detected by the same principle: a covert program still has to do things, and the things it must do leave traces.

The parts a covert collector must have

A defender is told the parts not in order to build one but because each part is a place to look. Any program that quietly collects and sends information must, at concept level, have:

  • a collection component that captures what it wants: keystrokes, screen contents, files, browsing, or audio and video from a device;
  • a staging component that holds the collected data on the machine until it can be sent;
  • an exfiltration component that sends it to the collector, usually disguised as ordinary traffic;
  • a persistence component so it survives a restart, which is the auto-start machinery of the earlier chapter;
  • often a concealment component to avoid notice, which in the worst case is the rootkit machinery of the previous chapter.

The defensive value is that each part leaves a distinct kind of trace, so knowing the parts tells a defender what to monitor:

PartThe trace a defender looks for
CollectionHooking of input or screen capture, unusual access to input devices
StagingAn unexpected growing file, data accumulating in a temporary area
ExfiltrationUnexplained outbound connections, the single most reliable indicator, seen off-host
PersistenceA start-up entry not in the baseline, from the auto-start audit
ConcealmentThe cross-view discrepancies of the rootkit chapter

Exfiltration is the one a covert collector cannot avoid: the data must leave the machine to be useful, and that departure is visible from the network and in the off-host logs, regardless of how well the program hides on the host. That is why egress monitoring, met in the Log4Shell case and again here, is such a powerful control against this whole category.

munotes.in258

Spyware and Keyloggers from the Defensive Side

Software and hardware keyloggers

A keylogger deserves a specific note because it has a form the others do not.

A software keylogger is a program, and it is detected and prevented like any covert program: by endpoint protection, by the traces above, and by controlling what may be installed.

A hardware keylogger is a physical device placed between a keyboard and a computer, or inside one. It has a property that matters for defence: because it captures keystrokes in hardware, before the operating system, no software running on the machine can see it, so software detection cannot find it. It also has a corresponding weakness: it is physical, so it is found by physical inspection and prevented by physical controls over access to machines. This is a rare case in this book where the defence is a lock and a look rather than a configuration, and it is worth knowing precisely because it defeats the software-only mindset.

Prevention and detection

The controls are the endpoint discipline that limits all malware, previewed here and treated fully in the Module 2 endpoint chapter:

Prevention:

  • Least privilege, so that a collector installed under an ordinary account can capture less and persist less easily; deep collection and system-wide keylogging generally need elevated rights.
  • Control over what may be installed, ideally application allow-listing so unapproved programs cannot run at all, which stops most spyware before it starts. Much spyware arrives bundled with something the user chose to install, which is the baiting route from the social-engineering block.
  • Control over what may be connected, restricting removable devices, which addresses both the bundled-download route and the hardware keylogger.
  • Patching and email and web filtering, to close the arrival routes.
  • Physical security of machines, for the hardware case.

Detection:

  • Endpoint detection tools watching for input hooking, screen capture, and the creation of persistence.
  • Egress monitoring for the exfiltration that a collector cannot avoid, which is the most reliable single signal.
  • The auto-start audit of the persistence chapter, which finds the survival mechanism.
  • Integrity and cross-view methods from the rootkit chapter where concealment is involved.
  • Physical inspection for hardware devices.

The unifying point, and the reason this chapter can be short: spyware and keyloggers are covert programs, and covert programs are caught by the traces of the things they must do, which are the same traces the last two chapters taught a defender to watch.

munotes.in259

Spyware and Keyloggers from the Defensive Side

A worked example, run as a defender

A finance team member reports that money moved from an account after they logged in normally, with no phishing they can recall. The team investigates the workstation.

  • Egress monitoring shows the machine made periodic connections to an unfamiliar external address, small and regular, at times unrelated to the user's activity. This is the exfiltration trace, and it is visible from the network without trusting the host.
  • The auto-start audit finds a start-up entry not in the baseline: the persistence trace.
  • Endpoint telemetry shows the responsible program hooking keyboard input: the collection trace, consistent with a keylogger that captured the banking credentials as they were typed.
  • Because concealment was involved, the analysts corroborate from clean examination rather than trusting the live system.

The response follows the system-hacking block: isolate the host, preserve evidence, treat it as compromised and rebuild from clean media, and, crucially, rotate every credential the user entered on that machine, because a keylogger captured them regardless of how strong they were, which is why the password chapters coming next insist that multi-factor authentication matters precisely because it survives a stolen password. The team also checks how the program arrived, finding it bundled with an unapproved download, which turns into a recommendation for application allow-listing.

Each trace corresponded to a part the collector could not do without, which is the chapter's method in practice.

What beginners get wrong

  • Thinking a covert program is undetectable because it hides on the host. It must still collect, persist and, above all, send the data, and those actions leave traces, most reliably the outbound connection seen off-host.
  • Trying to detect a hardware keylogger with software. It captures before the operating system, so software cannot see it; it is found by physical inspection and prevented by physical control.
  • Believing a strong password defeats a keylogger. A keylogger captures the password as typed, whatever its strength; multi-factor authentication is what limits the damage, which is why it recurs as the key control.
  • Forgetting the arrival route. Much spyware is bundled with a chosen download or arrives through phishing; controlling installation and filtering mail and web addresses the source.
  • Underrating egress monitoring. The data must leave to be useful, so its departure is the trace a collector cannot avoid.
  • Cleaning instead of rebuilding after a confirmed infection, and forgetting to rotate credentials the machine may have captured.

Quick revision

  • Spyware covertly collects and transmits information; a keylogger is the form that records keystrokes, capturing credentials as typed.
  • A covert collector must have collection, staging, exfiltration, persistence and often concealment; each part leaves a trace, and exfiltration, the outbound connection, is the one it cannot avoid and the most reliable signal, visible off-host.
  • Software keyloggers are detected and prevented like any covert program; hardware keyloggers capture before the operating system, so software cannot see them, and are found by physical inspection and prevented by physical control.
  • Prevention: least privilege, application allow-listing, control over connected devices, patching, mail and web filtering, physical security.
  • Detection: endpoint tools for input hooking and persistence creation, egress monitoring, the auto-start audit, integrity and cross-view methods, and physical inspection.
  • After a confirmed infection: rebuild from clean media and rotate every credential the machine may have captured; multi-factor authentication limits the damage of a stolen password.
munotes.in260

Spyware and Keyloggers from the Defensive Side

Test yourself

  1. What is the difference between spyware and a keylogger, and what do they have in common with a rootkit?

Spyware covertly collects information about a user or system and transmits it to a third party; a keylogger is the specific form that records keystrokes to capture credentials and other typed data. They share with a rootkit the instinct to remain unnoticed, so all three are covert programs, but spyware and keyloggers exist to harvest information whereas a rootkit exists to conceal an intrusion.

  1. Why does knowing the parts of a covert collector help a defender, and which part cannot be avoided?

Because each part, collection, staging, exfiltration, persistence and concealment, leaves a distinct kind of trace, so knowing the parts tells a defender what to monitor. Exfiltration cannot be avoided, because the collected data must leave the machine to be of any use, and that departure is visible as an outbound connection from the network and in off-host logs regardless of how well the program hides on the host.

  1. Why can software not detect a hardware keylogger, and how is one found?

Because a hardware keylogger captures keystrokes in the physical path between keyboard and computer, before the operating system processes them, so no software running on the machine can observe it. It is found by physical inspection of the machine and its connections and prevented by physical controls over who can access the hardware.

  1. Why is a strong password no defence against a keylogger, and what is?

Because a keylogger records the password exactly as it is typed, so its strength is irrelevant once it has been entered on the compromised machine. Multi-factor authentication limits the damage, because a captured password alone is then insufficient to authenticate, which is why it is emphasised as the key control against credential theft.

  1. What must be done to credentials after a confirmed keylogger infection, and why?

Every credential the user entered on the affected machine must be rotated, because the keylogger will have captured them as they were typed regardless of their strength or how they were stored elsewhere. The host itself should be rebuilt from clean media, since a confirmed covert infection means it can no longer be trusted, and the arrival route should be investigated to prevent recurrence.

Contents This chapter on its own page

munotes.in261

Chapter Fifty-Four

Encoding, Encryption and Hashing: Three Different Things

Syllabus topic Module 1, "Cryptography and Password Security Analysis: Differentiate between encryption and hashing mechanisms"

In one line

Encoding changes the representation of data and provides no security. Encryption hides data reversibly, with a key. Hashing produces a fixed fingerprint that cannot be reversed. Confusing them is the source of real breaches.

In examination wording: encoding is a reversible transformation of data into another format for compatibility or transport, requiring no key and providing no confidentiality; encryption is a reversible transformation using a key that renders data unreadable without that key; hashing is a one-way transformation producing a fixed-size digest from which the input cannot be recovered.

Why this distinction is worth a chapter

The three are constantly confused, in casual speech and in code, and the confusion is not harmless. A developer who "encodes" a password thinks they have protected it and has not. A tester who sees Base64 in a request and reports it as "encrypted, therefore secure" is wrong, and one who sees it and recognises it as reversible has found that sensitive data is effectively in the clear. The word chosen determines the security conclusion, so the words must be exact.

The quickest way to keep them apart is to ask two questions of any transformation: is there a key? and can it be reversed? The answers place it uniquely.

Key?Reversible?Purpose
EncodingNoYes, by anyoneCompatibility, transport
EncryptionYesYes, with the keyConfidentiality
HashingNoNoIntegrity, fingerprints, password storage

Encoding

Encoding transforms data from one representation to another so that it can be stored or transmitted correctly. Base64, which represents binary data using a limited set of text characters, is the example everyone meets: it lets a binary attachment travel through a text-only email system. URL encoding, which represents special characters so they can appear in a web address, is another.

The defining properties, and the only ones that matter for security:

  • No key. The transformation is fixed and public.
  • Reversible by anyone. Anyone who recognises the encoding can reverse it, with no secret, using standard tools.
  • No confidentiality whatsoever. Encoded data is exactly as readable as the original to anyone who cares to decode it.

So encoding is not a security mechanism, and this is the sentence to carry out of the chapter. Base64 looks unreadable to a human at a glance, which is exactly why it is mistaken for protection, but converting it back is trivial and requires no secret. Data that matters must be encrypted or hashed; encoding it protects nothing.

Where encoding appears in security work is as obfuscation, not protection: attackers encode a payload to slip it past a filter that recognises the plain form, which is why the input-validation chapter warns that filtering a dangerous pattern is weak when the attacker controls the encoding. That is encoding used to evade, not to secure, and it underlines the point: the transformation carries no secret, so it defends nothing and can be undone by attacker or defender alike.

munotes.in262

Encoding, Encryption and Hashing: Three Different Things

Encryption

Encryption transforms data using a key so that it is unreadable without that key, and reversible with it. The unencrypted data is plaintext, the encrypted form is ciphertext, and the transformation runs both ways: encrypt with the key, decrypt with the (same or corresponding) key.

The defining properties:

  • A key is required. The security rests entirely on the key, not on the method, which is assumed to be public. This is a foundational principle, that a cryptosystem should be secure even if everything about it except the key is known, and it is why home-made secret algorithms are distrusted.
  • Reversible with the key, and, when the algorithm is sound, infeasible to reverse without it.
  • Purpose: confidentiality. Encryption is how data is kept readable only to those holding the key, in transit and at rest.

Encryption is the right tool when data must be read again by an authorised party: a message the recipient must decrypt, a file the owner must reopen, a database the application must query. The next chapter divides it into its two forms, symmetric and asymmetric.

The critical limit, which sets up the password chapter: encryption is reversible by design. That is its purpose and, for one particular job, its fatal flaw. If you encrypt something, a key exists that turns it back, and whoever holds that key, including an attacker who steals it, gets the original. For data you must read again, that is exactly what you want. For a password, it is exactly what you do not.

Hashing

Hashing transforms input of any size into a fixed-size digest, and it is one-way: you cannot recover the input from the digest. There is no key.

The defining properties:

  • No key. A hash is deterministic and public: the same input always gives the same digest, computable by anyone.
  • One-way. Given a digest, finding the input that produced it should be infeasible. This is what distinguishes hashing from encryption most sharply: there is no reverse operation, not merely a reverse operation that needs a key.
  • Fixed size. Any input, from one character to a large file, produces a digest of the same length.
  • Purpose: fingerprints. A hash is a compact, verifiable fingerprint of data, used to detect change (integrity), to store passwords without keeping them, and to index data.

The property that makes hashing useful for the coming password chapters is the combination of deterministic and one-way: you can check whether two inputs are the same by comparing their digests, without ever being able to recover either input from its digest. That is precisely what password storage needs, and it is why passwords are hashed rather than encrypted, which is the subject of a whole chapter shortly.

munotes.in263

Encoding, Encryption and Hashing: Three Different Things

Hashing also underlies the integrity idea from the CIA chapter (a changed file has a changed hash) and the digital-signature and certificate machinery, and its required properties are the next-but-one chapter.

A worked example: reading a login request

A tester examines a web login request and sees the password field carrying cGFzc3dvcmQxMjM=.

  • It is Base64 encoding, recognisable by its character set and padding. Reversing it, with no key, yields the password in the clear.
  • The conclusion is not "the password is encrypted"; it is "the password is effectively transmitted in the clear, merely encoded, so anyone who can read the request reads the password". If the connection is also not encrypted with TLS, that is a serious finding.
  • The fix is not "encode it differently" but to protect the channel with TLS (transport encryption) and, at the server, to hash the password for storage, never to encode or encrypt it.

The same misreading in reverse is equally common: seeing a stored value that is a fixed-length hexadecimal digest and calling it "encrypted". It is hashed, which is why the site cannot email the user their forgotten password, only reset it, a behaviour that is itself evidence the storage is done correctly.

What beginners get wrong

  • Calling Base64 or any encoding "encrypted". It has no key and is reversible by anyone; it provides no confidentiality at all.
  • Thinking unreadable-to-a-human means secure. Encoded data looks scrambled and is trivially decoded. Appearance is not protection.
  • Encrypting passwords. Encryption is reversible, so a stored key means stolen passwords; passwords are hashed. This is the next-but-one chapter's whole point.
  • Believing hashing is just encryption without sharing the key. Hashing has no reverse operation at all, not a reverse operation gated by a key.
  • Reporting encoded sensitive data as safe. Encoded is as readable as plaintext; the finding is that the data is effectively in the clear.
  • Trusting a secret algorithm. Security rests on the key, with the method assumed public; home-made secret methods are distrusted for exactly that reason.

Quick revision

  • Ask two questions: is there a key? and can it be reversed?
  • Encoding: no key, reversible by anyone, no security. Base64, URL encoding. A representation change, and in attacks a means of evasion, never protection.
  • Encryption: a key, reversible with it, for confidentiality; plaintext to ciphertext and back. Security rests on the key, method assumed public. Reversible by design, which is its purpose and, for passwords, its flaw.
  • Hashing: no key, one-way, fixed-size digest, for fingerprints: integrity, password storage, indexing. Deterministic, so equal inputs give equal digests, without any way back.
  • Passwords are hashed, never encoded or encrypted; a site that can only reset, not resend, a password is storing them correctly.
munotes.in264

Encoding, Encryption and Hashing: Three Different Things

Test yourself

  1. State the two questions that distinguish encoding, encryption and hashing, and give the answers for each.

Is there a key, and can it be reversed. Encoding has no key and is reversible by anyone, so it provides no security; encryption has a key and is reversible only with it, providing confidentiality; hashing has no key and is not reversible at all, providing a one-way fingerprint.

  1. Why is Base64 not a security mechanism, and what mistake does treating it as one cause?

Because it has no key and can be reversed by anyone using standard tools, so encoded data is exactly as readable as the original. Treating it as security causes sensitive data, such as a password, to be left effectively in the clear while appearing protected, and causes a tester to wrongly report encoded data as safe.

  1. Why is encryption the wrong tool for storing passwords despite being reversible with a key?

Precisely because it is reversible: a key exists that turns the ciphertext back into the password, so whoever holds that key, including an attacker who steals it alongside the data, recovers every password. Password storage needs a transformation with no way back, which is hashing.

  1. How does hashing differ from encryption at the most fundamental level?

Encryption is reversible with the appropriate key, so a reverse operation exists; hashing is one-way, so there is no reverse operation at all and the input cannot be recovered from the digest. Hashing also uses no key, whereas encryption's security depends entirely on the key.

  1. A tester sees a stored credential value that is a fixed-length hexadecimal string, and the site can reset but not resend forgotten passwords. What does this indicate?

That the passwords are hashed rather than encrypted or encoded, which is correct: the fixed-length digest is a one-way fingerprint, and the inability to resend the original password, only to reset it, is direct evidence that the site does not hold the passwords in any recoverable form.

Contents This chapter on its own page

munotes.in265

Chapter Fifty-Five

Symmetric and Asymmetric Encryption at Concept Level

Syllabus topic Module 1, "Cryptography and Password Security Analysis: Differentiate between encryption and hashing mechanisms"

In one line

Symmetric encryption uses one shared key to encrypt and decrypt, and is fast but faces the problem of sharing the key. Asymmetric encryption uses a public and a private key, which solves key distribution but is slow, so real systems combine the two.

In examination wording: symmetric encryption uses a single secret key shared by both parties for encryption and decryption; asymmetric (public-key) encryption uses a mathematically related key pair, a public key that may be shared freely and a private key kept secret, such that data encrypted with one is decrypted only with the other; practical systems use asymmetric methods to exchange a symmetric key and symmetric methods to protect the data.

Symmetric encryption

How it works. One key. The same secret value both encrypts the plaintext into ciphertext and decrypts it back. Both parties must hold the same key, and anyone who has it can both encrypt and decrypt.

Its strengths. It is fast, efficient enough to encrypt large volumes of data and continuous streams, and it is well understood. The standard modern symmetric cipher is AES, which appears in the wireless chapter as the basis of WPA2 and WPA3 and underlies most bulk encryption in use.

Its one hard problem: key distribution. If two parties must share a secret key before they can communicate securely, how do they share it? They cannot send it over the very channel they are trying to protect, because anyone reading that channel would capture the key. For two people who can meet, this is easy; for a browser connecting to a web server it has never contacted, across the open internet, it is the central difficulty. This problem is what asymmetric encryption was invented to solve, and a student who understands the problem understands why asymmetric encryption matters.

A second problem at scale: with symmetric keys, every pair of parties who wish to communicate privately needs its own shared key, so the number of keys grows explosively with the number of participants.

Asymmetric encryption

How it works. A key pair: a public key that may be published to anyone, and a private key kept secret by its owner. The two are mathematically related so that what one key encrypts, only the other can decrypt, and, crucially, knowing the public key does not reveal the private key.

This asymmetry enables two distinct uses, and keeping them separate is examinable:

  • For confidentiality: anyone encrypts a message with the recipient's public key, and only the recipient, holding the matching private key, can decrypt it. So anyone can send a secret to the owner of a public key, and only that owner can read it. No prior shared secret is needed, which is exactly the key-distribution problem solved.
  • For authenticity (signing): the owner encrypts (signs) with their private key, and anyone can verify with the public key. Since only the owner has the private key, a valid signature proves it came from them. This is the digital-signature idea, and it provides the authenticity and non-repudiation the CIA chapter set aside.
munotes.in266

Symmetric and Asymmetric Encryption at Concept Level

Its weakness: speed. Asymmetric operations are far slower than symmetric ones, too slow to encrypt large amounts of data directly. So it is not used for bulk encryption.

Its dependency: trust in the public key. The scheme rests on knowing that a public key really belongs to the party you think it does. An attacker who substitutes their own public key for the recipient's can read what you send. Establishing that a public key is genuine is the job of certificates and the certificate authorities behind them, which is why the man-in-the-middle chapter can be defeated by a certificate check: the fake server cannot present a genuinely trusted certificate for the real name.

A worked example: the hybrid arrangement in HTTPS

Neither alone is ideal: symmetric is fast but cannot easily share its key, asymmetric shares keys freely but is slow. So virtually every real system combines them, and understanding the combination explains TLS, secure messaging and much else.

The arrangement:

  1. Use asymmetric encryption once, at the start, to agree or exchange a symmetric key. Because only a small key is protected this way, the slowness does not matter.
  2. Use that symmetric key, with a fast cipher, to encrypt the actual data for the rest of the session.

So asymmetric encryption does the hard part, establishing a shared secret between parties with no prior relationship, and symmetric encryption does the bulk work, protecting the data efficiently. This is exactly what happens when a browser connects to a website over HTTPS: an asymmetric exchange (verified by the site's certificate) establishes a session key, and the page contents travel under fast symmetric encryption. The TLS chapter in Module 2 develops this handshake.

A refinement worth naming, because it appeared in the Heartbleed case: forward secrecy arranges the key exchange so that a fresh symmetric key is used each session and is not recoverable from the server's long-term private key, so that capturing traffic and later stealing the private key does not decrypt the past. Modern systems use it, which is why compromise of a server's key is less catastrophic than it once was.

The comparison

SymmetricAsymmetric
KeysOne shared secretA public and a private key
SpeedFast; suits bulk dataSlow; suits small data
Key distributionThe hard problemSolved: publish the public key
Keys needed among N partiesGrows explosivelyOne pair each
Used forEncrypting the actual dataExchanging a key; signing
ExampleAESRSA and elliptic-curve methods
In a real sessionProtects the dataEstablishes the shared key
munotes.in267

Symmetric and Asymmetric Encryption at Concept Level

The one-sentence summary a student should be able to give: asymmetric encryption solves the key-distribution problem and is slow, symmetric encryption is fast but cannot easily share its key, so systems use asymmetric to exchange a symmetric key and symmetric to protect the data.

Where this appears in the book

  • TLS and HTTPS (Module 2): the hybrid handshake, verified by a certificate.
  • Wireless (Module 2): WPA2 and WPA3 use AES, a symmetric cipher, with a key established by the four-way or SAE handshake.
  • Digital signatures and certificates: the signing use of asymmetric keys, providing authenticity and the trust that makes public keys usable.
  • Password storage (next chapters): notably, none of this. Passwords are hashed, not encrypted, and the distinction from the previous chapter is why.

What beginners get wrong

  • Confusing the two uses of a key pair. Encrypt with the recipient's public key for confidentiality; sign with your own private key for authenticity. Reversing them is a classic error.
  • Thinking asymmetric encryption replaced symmetric. It did not; it solved key distribution. Systems use both, asymmetric to share a key and symmetric to encrypt the data.
  • Believing asymmetric is stronger because it is newer or more elaborate. They serve different purposes; asymmetric is slower and used sparingly for that reason.
  • Forgetting the trust problem. Asymmetric encryption is only as good as the assurance that a public key belongs to the right party, which is what certificates provide.
  • Assuming a shared key can be sent over the channel being protected. It cannot without exposing it, which is the key-distribution problem itself.
  • Applying any of this to passwords. Passwords are hashed, not encrypted; this chapter is about protecting data that must be read again.

Quick revision

  • Symmetric: one shared key, fast, for the actual data; its hard problem is key distribution, and keys grow explosively with the number of parties. Example: AES.
  • Asymmetric: a public key (shareable) and a private key (secret); mathematically related, and the public key does not reveal the private. Slow.
  • Two uses: encrypt with the recipient's public key for confidentiality; sign with your own private key for authenticity (and non-repudiation).
  • Asymmetric solves key distribution; its dependency is trust in the public key, provided by certificates.
  • Hybrid: asymmetric to exchange a symmetric key, then symmetric to protect the data; this is HTTPS. Forward secrecy uses a fresh session key not recoverable from the long-term private key.

Test yourself

  1. What problem does asymmetric encryption solve that symmetric encryption cannot, and why does that problem arise?
munotes.in268

Symmetric and Asymmetric Encryption at Concept Level

Key distribution: how two parties who have never met and share the open channel establish a secret key without sending it over that channel, where anyone could capture it. It arises because symmetric encryption requires both parties to already hold the same secret, which is exactly what they cannot safely exchange in the open.

  1. Describe the two distinct uses of an asymmetric key pair.

For confidentiality, a sender encrypts with the recipient's public key and only the recipient's private key can decrypt, so anyone can send a secret that only the owner can read. For authenticity, the owner signs with their own private key and anyone verifies with the public key, so a valid signature proves it came from the owner, since only they hold the private key.

  1. Why do real systems combine symmetric and asymmetric encryption rather than using one?

Because asymmetric encryption solves key distribution but is too slow for bulk data, while symmetric encryption is fast but cannot easily share its key. The hybrid uses asymmetric encryption once to exchange a symmetric session key, then uses that symmetric key with a fast cipher to protect the actual data, gaining both properties.

  1. On what does the security of asymmetric encryption depend besides the secrecy of the private key?

On the assurance that a public key genuinely belongs to the party it is believed to belong to. If an attacker substitutes their own public key, they can read messages intended for the real owner, so certificates and the authorities that issue them exist to bind a public key to an identity and provide that trust.

  1. Why does none of this apply to password storage?

Because encryption, symmetric or asymmetric, is reversible by design and is for data that must be read again, whereas a password must never be recoverable from its stored form. Passwords are therefore hashed, a one-way operation with no way back, so that a stolen store does not reveal them.

Contents This chapter on its own page

munotes.in269

Chapter Fifty-Six

Hash Functions and the Properties They Must Have

Syllabus topic Module 1, "Cryptography and Password Security Analysis: ... cryptographic weaknesses"

In one line

A cryptographic hash function must be one-way, must give completely different digests for even slightly different inputs, and must make it infeasible to find two inputs with the same digest. When people say a hash "broke", they mean one of these properties failed, and which one determines what is still safe.

In examination wording: a cryptographic hash function maps arbitrary input to a fixed-size digest and must satisfy preimage resistance (given a digest, it is infeasible to find an input producing it), second-preimage resistance (given an input, it is infeasible to find a different input with the same digest), and collision resistance (it is infeasible to find any two distinct inputs with the same digest); the avalanche effect requires that a small change in input changes the digest extensively.

Why the properties matter

The previous chapter said hashing produces a one-way fingerprint. That is not automatic; a function is only a cryptographic hash if it has specific properties, and each property is what makes a particular use safe. So the properties are not abstract: each one corresponds to an attack it prevents, and when a hash loses a property, the uses that depended on it become unsafe while the others remain fine. That is the practical payoff of this chapter and the reason it repays care.

The properties

Preimage resistance (one-way). Given a digest, it is infeasible to find any input that produces it. This is what "one-way" means precisely: you cannot run the function backwards. It is the property that lets a hash store a password, because an attacker who steals the digest cannot compute the password from it. Without it, the whole idea of storing a fingerprint instead of the data collapses.

Second-preimage resistance. Given one specific input, it is infeasible to find a different input with the same digest. This is what lets a hash certify integrity: if you publish a file and its hash, no one can substitute a different file that matches the same hash, so a reader who checks the hash knows the file is the one you published.

Collision resistance. It is infeasible to find any two distinct inputs that share a digest, where the attacker is free to choose both. This is stronger than second-preimage resistance, because the attacker controls both inputs rather than being handed one, and it is the property that matters for digital signatures: if an attacker could produce two documents with the same hash, they could get one signed and claim the signature applies to the other.

The avalanche effect. A small change in the input, even a single character, changes the digest completely and unpredictably, so that digests reveal nothing about how similar their inputs were. Without it, similar inputs would produce similar digests, leaking information and aiding attacks. It is a property of any good hash and is what makes a digest a useful fingerprint: password1 and password2 produce digests with no visible relationship.

munotes.in270

Hash Functions and the Properties They Must Have

Two further practical properties: the function is deterministic (the same input always gives the same digest, or comparison would be impossible) and fast to compute (for general hashing). That last one, fast, becomes a problem for passwords, which is the subject of the next chapter and the one place where a general virtue is a specific vice.

The birthday problem and why collision resistance is harder

A point examiners like, because it explains why hashes are the length they are.

Intuitively, finding a collision seems as hard as finding a preimage. It is not, and the reason is the birthday problem: in a room of only 23 people, the chance that two share a birthday exceeds a half, far sooner than intuition suggests, because there are many possible pairs. The same mathematics applies to hashes: finding any two inputs that collide takes roughly the square root of the effort of finding a preimage for a specific digest.

The consequence is that collision resistance provides only about half the security bits that the digest length suggests, so a hash needs to be twice as long to resist collision attacks as to resist preimage attacks. This is why modern hashes produce 256-bit or longer digests: to leave adequate margin against the birthday-bounded collision search.

What it meant that MD5 and SHA-1 "broke"

Now the payoff, and the distinction that a strong answer makes.

MD5 and SHA-1 were widely used hash functions, and both were shown to be collision-broken: researchers found methods to produce two different inputs with the same digest far faster than should be possible, and eventually demonstrated real colliding files. This is a failure of collision resistance.

The examinable subtlety is what this does and does not compromise:

  • Digital signatures and certificates, which rely on collision resistance, became unsafe with these hashes, because an attacker able to craft a collision could obtain a signature on one document and transfer it to another. Certificate authorities moved off SHA-1 for exactly this reason.
  • Second-preimage resistance was not broken to the same degree: it remained infeasible to take one given file and find a different file matching it. So checking a known file against a published MD5 for accidental corruption still worked, even though it was no longer safe against a determined attacker who controls both files.
  • Preimage resistance largely held for longer: computing an input from a digest remained infeasible.

So a precise statement is: MD5 and SHA-1 failed collision resistance, which broke their use in signatures and certificates, while their other uses degraded more slowly. A student who says "MD5 is broken so it cannot be used for anything" is roughly right in practice, because you should not build on a function with any broken property, but a student who can say which property broke and which uses that affects understands the subject.

munotes.in271

Hash Functions and the Properties They Must Have

For password storage, the fatal problem with MD5 and SHA-1 turns out not to be any of these breaks but their speed, which the next chapter explains, and that is why the correct answer to "can I store passwords with SHA-256?" is also no, even though SHA-256 is not broken at all.

The modern hashes

For general-purpose hashing and integrity, the SHA-2 family (including SHA-256 and SHA-512) and SHA-3 are the current standards, unbroken, with digests long enough to give collision-resistance margin.

For password storage specifically, none of the general-purpose hashes is appropriate, because they are fast; the purpose-built slow hashes (bcrypt, scrypt, Argon2) are used instead, for reasons the next chapter gives in full.

The distinction to carry: a fast, unbroken hash like SHA-256 is correct for integrity and fingerprints and wrong for passwords; a slow hash like Argon2 is correct for passwords. Both are needed, for different jobs.

A worked example

A tester examines how an application uses hashes and reports on each use against the properties.

  • File-download integrity. The site publishes SHA-256 digests beside downloads. Correct: SHA-256 is unbroken and fast, which is what integrity checking wants, and second-preimage resistance ensures a substituted file will not match.
  • Digital signatures using SHA-1. A finding: SHA-1's collision resistance is broken, and signatures depend on it, so an attacker able to craft a collision could misuse a signature. Move to SHA-256 or better.
  • Password storage using unsalted SHA-256. A finding, and the most serious, but not because SHA-256 is broken; it is not. The problem is that SHA-256 is fast, so an attacker with the stolen digests can try enormous numbers of guesses cheaply. The fix is a purpose-built slow hash with a salt, the next chapter's subject.
  • A digest used to detect accidental corruption in transit, using MD5. Weak but not the priority: for accidental corruption MD5 still functions, though there is no reason to prefer a broken hash when SHA-256 is available.

The report ranks these by the property at stake and the use it supports, which is precisely what knowing the properties allows.

What beginners get wrong

  • Thinking "broken" means useless for everything. A hash can fail one property while others hold; which property broke determines which uses become unsafe. In practice you move off it entirely, but the reasoning matters.
  • Believing collision resistance and preimage resistance are equally hard. The birthday problem makes finding any collision far easier than finding a specific preimage, which is why hashes are long.
  • Using SHA-256 for passwords because it is unbroken. It is unbroken and fast, and fast is the wrong property for passwords; a slow purpose-built hash is required.
  • Confusing second-preimage with collision resistance. Second-preimage: you are given one input and must match it. Collision: you choose both inputs freely, which is easier and what signatures need protection against.
  • Ignoring the avalanche effect. Without it, similar inputs give similar digests and leak information; a good hash makes a one-character change alter the digest completely.
  • Preferring a broken hash where an unbroken one is available. Even for uses a broken hash still technically serves, there is no reason not to use a current one.
munotes.in272

Hash Functions and the Properties They Must Have

Quick revision

  • Cryptographic hash properties: preimage resistance (can't reverse a digest to an input; enables password storage), second-preimage resistance (can't match a given input; enables integrity), collision resistance (can't find any two colliding inputs; enables signatures), and the avalanche effect (a tiny input change alters the digest completely). Also deterministic and, for general use, fast.
  • The birthday problem makes finding any collision about the square root of the preimage effort, so collision resistance needs roughly double the digest length, which is why modern digests are long.
  • MD5 and SHA-1 failed collision resistance, breaking their use in signatures and certificates; other uses degraded more slowly. Move off them entirely.
  • Current: SHA-2 (SHA-256, SHA-512) and SHA-3 for general hashing and integrity; bcrypt, scrypt, Argon2 for passwords.
  • A fast unbroken hash (SHA-256) is right for integrity and wrong for passwords; a slow hash (Argon2) is right for passwords.

Test yourself

  1. State the three security properties of a cryptographic hash and the use each one enables.

Preimage resistance, that a digest cannot be reversed to an input, which enables storing passwords as digests; second-preimage resistance, that a given input cannot be matched by a different one, which enables integrity checking of a published file; and collision resistance, that no two distinct inputs can be found sharing a digest, which enables digital signatures.

  1. What is the avalanche effect and why is it necessary?

That a small change in the input, even a single character, changes the digest extensively and unpredictably. It is necessary so that digests reveal nothing about the similarity of their inputs; without it, similar inputs would produce similar digests, leaking information and undermining the digest's value as a fingerprint.

  1. Why does the birthday problem mean a hash must be longer to resist collisions than to resist preimages?

Because finding any two inputs that collide, where the attacker chooses both, takes roughly the square root of the effort of finding an input for a specific digest, since there are many possible pairs. Collision resistance therefore provides only about half the security bits of the digest length, so the digest must be roughly twice as long to give adequate collision-resistance margin.

munotes.in273

Hash Functions and the Properties They Must Have

  1. Which property did MD5 and SHA-1 lose, and which uses did that make unsafe?

Collision resistance: methods were found to produce two different inputs with the same digest. That made their use in digital signatures and certificates unsafe, because an attacker able to craft a collision could obtain a signature on one document and apply it to another, which is why certificate authorities moved away from SHA-1.

  1. Why is SHA-256, although unbroken, still the wrong choice for storing passwords?

Because SHA-256 is designed to be fast, and speed lets an attacker who has stolen the stored digests try an enormous number of password guesses cheaply. Password storage instead requires a deliberately slow, purpose-built hash such as bcrypt, scrypt or Argon2, so that each guess is expensive; the property that makes SHA-256 excellent for integrity makes it unsuitable here.

Contents This chapter on its own page

munotes.in274

Chapter Fifty-Seven

Why a Password Is Never Encrypted: Storage and Salting

Syllabus topic Module 1, "Cryptography and Password Security Analysis: ... password storage models, salting techniques"

In one line

A password store must survive being stolen. So passwords are never encoded and never encrypted, both of which can be reversed; they are put through a one-way hash with a per-user random salt, using a deliberately slow algorithm, so that a stolen database is not a stolen list of passwords.

In examination wording: passwords are stored as salted hashes rather than in plaintext, encoded or encrypted form, so that the stored value never reveals the password even if the store is disclosed; a salt is unique random data combined with each password before hashing to defeat precomputed lookups and to hide identical passwords; a purpose-built slow hash (bcrypt, scrypt, Argon2) is used to make large-scale guessing infeasible.

The design goal: assume the database is stolen

Password storage is designed for the day the database is stolen, because databases are stolen regularly, through the very flaws this book covers: SQL injection, a compromised server, a leaked backup, an insider. The question is not how to prevent theft, which is a separate and never-complete effort, but what an attacker gets when they succeed.

If passwords are stored in a recoverable form, the answer is: every password, immediately. If they are stored correctly, the answer is: a set of values from which the passwords cannot practically be recovered, buying every user time to change their password before it is cracked, and protecting entirely those with strong passwords.

So the correct measure of a password store is not how well it is protected but how little it yields when it fails. That reframing is the chapter.

Why not encoding, and why not encryption

The previous chapters answer both.

Not encoding, because encoding has no key and is reversed by anyone. Storing an encoded password is storing a plaintext password with extra steps.

Not encryption, and this is the one people reach for, because it feels secure. It is the wrong tool, for a precise reason: encryption is reversible with a key, so the system must hold that key somewhere to check passwords. An attacker who steals the database will, in the same class of breach, very often steal the key too, and then every password decrypts. Encryption for passwords adds a single point of total failure, the key, and buys nothing that hashing does not.

The rule, stated once and carried: you do not need to know a user's password to check it. You only need to know whether the password they just typed matches the one set before. A one-way hash does exactly that, and nothing more, which is exactly the right amount.

How password checking works with a hash

To store a password, compute its hash and store the hash. To check a login, hash what the user typed and compare it with the stored hash. If they match, the password is correct. The password itself is never stored and never recovered, which is why a correctly built site can only ever reset a forgotten password, never resend it. A site that emails you your existing password has proven it stores passwords recoverably, which is a finding in itself.

munotes.in275

Why a Password Is Never Encrypted: Storage and Salting

Why a bare hash is not enough: the salt

There is a flaw in "just hash it", and it follows from the hash being deterministic: the same input always gives the same digest. So two users with the same password get the same stored hash, and that has two bad consequences an attacker exploits:

  • Identical passwords are visible. Anyone who steals the store sees which users share a password, and cracking one cracks all of them.
  • Precomputation works. An attacker can compute the hashes of millions of common passwords once, in advance, and store the results in a giant lookup table (a rainbow table in its space-optimised form). Then, for any stolen hash, they look it up instead of cracking it. The expensive work is done once and reused against every victim.

A salt defeats both. A salt is a chunk of random data, unique to each password, combined with the password before hashing. Now:

  • Two users with the same password have different salts, so different stored hashes, so identical passwords are no longer visible and cracking one does not crack the other.
  • A precomputed table is useless, because it would have had to be built for this specific random salt, which the attacker could not have anticipated. The attacker is forced back to cracking each password individually, at full cost.

The salt is stored alongside the hash, and it does not need to be secret. Its job is uniqueness and unpredictability, not secrecy: even knowing the salt, the attacker must still do the full per-password work, which is exactly what the salt forces.

The demonstration

This program shows both facts: without a salt, identical passwords hash identically (the flaw); with a per-user salt, they do not (the fix). It is a safe demonstration of a defence: it stores nothing, sends nothing, and attacks nothing. The salts are fixed here only so the output is reproducible; in real code each salt comes from a secure random source.

import hashlib


def sha256_hex(text):
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


# Two users happen to choose the SAME password.
password = "sunshine"

# Without a salt, identical passwords hash to identical digests.
print("No salt (the problem):")
print("  alice:", sha256_hex(password)[:16], "...")
print("  bob:  ", sha256_hex(password)[:16], "...")
print("  same digest:", sha256_hex(password) == sha256_hex(password))

# A salt is random per user. Here two salts are FIXED so the output is
# reproducible; in real code each salt comes from a secure random source.
salt_alice = "a1b2c3d4"
salt_bob = "e5f6a7b8"

print("With a per-user salt (the fix):")
print("  alice:", sha256_hex(salt_alice + password)[:16], "...")
print("  bob:  ", sha256_hex(salt_bob + password)[:16], "...")
print("  same digest:", sha256_hex(salt_alice + password) == sha256_hex(salt_bob + password))
munotes.in276

Why a Password Is Never Encrypted: Storage and Salting

No salt (the problem):
  alice: a941a4c4fd0c01cd ...
  bob:   a941a4c4fd0c01cd ...
  same digest: True
With a per-user salt (the fix):
  alice: fd1ee781cd05aebf ...
  bob:   e58318ed6ead68a1 ...
  same digest: False

Alice and Bob chose the same password. Without a salt their stored digests are identical, so an attacker who cracks one has cracked both and a precomputed table finds them at once. With a salt the digests differ completely, and no precomputed table could have anticipated the salts. That is the entire argument for salting, shown rather than asserted.

Why the hash must be slow

One more piece, and it is why SHA-256 in the demonstration is not the final answer. SHA-256 is fast by design, which is exactly what integrity checking wants and exactly what password storage does not. An attacker with a stolen database can compute billions of fast hashes per second, so even salted, a weak password falls quickly.

Password storage therefore uses a deliberately slow function built for the purpose: bcrypt, scrypt or Argon2. These are tuned so that a single hash takes a meaningful fraction of a second, and can be made slower as hardware improves, and the better ones (scrypt, Argon2) also require a large amount of memory, which defeats the specialised fast-cracking hardware attackers use. That deliberate cost is invisible to a user logging in once, but it turns an attacker's billions of guesses per second into a few thousand, which is the difference between cracking a store in an hour and in centuries.

So the complete password storage model, the phrase MU uses, is: a purpose-built slow hash (bcrypt, scrypt or Argon2), with a unique random salt per password, and never the password itself, an encoding of it, or a reversible encryption of it.

A refinement to name: a pepper is an additional secret value, the same for all passwords, kept separately from the database (for example in the application's configuration or a hardware module) rather than stored with each hash. Because it is not in the database, a database-only theft does not reveal it, adding a further barrier. It supplements the salt; it does not replace it.

A worked example

A tester reviews how an application stores passwords, against the model.

  • Passwords stored as plaintext. The worst case: a stolen database is a stolen password list. Every user must change their password, and because of reuse, their accounts elsewhere are at risk too.
  • Passwords stored encrypted. Better in appearance, and still wrong: the decryption key is in the application, so a breach that reaches the database usually reaches the key, and all passwords decrypt. It is a single point of total failure.
  • Passwords stored as unsalted SHA-256. Fast and unsalted, so identical passwords are visible and a precomputed table cracks common ones instantly. A serious finding despite SHA-256 being unbroken.
  • Passwords stored as salted bcrypt. Correct: per-user salts defeat precomputation and hide shared passwords, and the slow hash makes bulk guessing infeasible, so a stolen store yields only the weakest passwords and only slowly.
munotes.in277

Why a Password Is Never Encrypted: Storage and Salting

The recommendation is the model: migrate to a salted slow hash, and, since the stored form cannot be converted, do it by re-hashing each password at the user's next login. The tester also notes that the strongest protection for the users is the next chapter's: even a perfectly stored password can be phished or guessed, so multi-factor authentication is what limits the damage.

What beginners get wrong

  • Encrypting passwords. Reversible, so a stolen key means stolen passwords; a single point of total failure. Hash them.
  • Believing a plain SHA-256 hash is safe storage. It is unsalted and fast: precomputed tables and billions of guesses per second defeat it. Salt, and use a slow hash.
  • Thinking the salt must be secret. It need not be; it is stored with the hash. Its job is uniqueness, so precomputation cannot anticipate it, not secrecy.
  • Reusing one salt for everyone. That restores the visibility of shared passwords and re-enables precomputation for that one salt. Salts are per-user.
  • Treating a hash's speed as a virtue. Fast is right for integrity and wrong for passwords, where slow is the point.
  • A site that emails your existing password. Direct evidence it stores passwords recoverably; a finding.

Quick revision

  • Design goal: assume the store is stolen; measure it by how little it yields, not how well it is protected.
  • Not encoding (no key, reversible by anyone) and not encryption (reversible with a key that a breach usually also steals). Hash: one-way, so a stolen store never reveals the passwords; check a login by hashing the input and comparing.
  • A correct site can only reset, never resend, a forgotten password.
  • A salt is unique random per-user data added before hashing; it hides identical passwords and defeats precomputed tables. Stored with the hash, and need not be secret.
  • The hash must be deliberately slow (bcrypt, scrypt, Argon2; the memory-hard ones also defeat cracking hardware); fast hashes make bulk guessing cheap.
  • Model = slow purpose-built hash + unique random salt + never the recoverable password. A pepper (a separate secret, not in the database) can supplement the salt.
munotes.in278

Why a Password Is Never Encrypted: Storage and Salting

Test yourself

  1. Why are passwords hashed rather than encrypted?

Because encryption is reversible with a key, so the system must hold that key to check passwords, and a breach that steals the database very often steals the key as well, decrypting every password. Hashing is one-way, so a stolen store never reveals the passwords, and the system can still check a password by hashing the input and comparing without ever being able to recover it.

  1. What two problems does a salt solve, and must it be secret?

It hides the fact that two users share a password, because a deterministic hash would otherwise give them identical stored digests, and it defeats precomputed lookup tables such as rainbow tables, because a table would have had to be built for the specific random salt. It need not be secret; it is stored alongside the hash, since its purpose is uniqueness and unpredictability rather than secrecy.

  1. In the demonstration, why do the two users have the same stored digest without a salt and different digests with one?

Because a hash is deterministic, so the same password produces the same digest, and without a salt two identical passwords therefore collide. A per-user salt makes each input different before hashing, so the digests differ completely and no precomputed table built without knowledge of the salts can match them.

  1. Why must the password hash be deliberately slow, and what is used instead of a fast hash like SHA-256?

Because an attacker with a stolen database can compute billions of fast hashes per second, so even salted, weak passwords fall quickly. A purpose-built slow function, bcrypt, scrypt or Argon2, is used so that each guess costs a meaningful fraction of a second and, for the memory-hard functions, a large amount of memory, making large-scale guessing infeasible while remaining unnoticeable to a legitimate login.

  1. What is the complete password storage model MU refers to, and what does a pepper add?

A purpose-built slow hash with a unique random per-user salt, storing neither the password nor any encoded or reversibly encrypted form of it. A pepper is an additional secret value common to all passwords but kept separately from the database, so that a database-only breach does not reveal it, adding a further barrier on top of the per-user salt.

Contents This chapter on its own page

munotes.in279

Chapter Fifty-Eight

How Passwords Are Attacked, and the Arithmetic of a Keyspace

Syllabus topic Module 1, "System Hacking and Privilege Escalation Concepts: Analyze password cracking methods ... from a defensive perspective"

In one line

Passwords are attacked by guessing, in bulk and cleverly: dictionary attacks try likely words, brute force tries every combination, rainbow tables trade storage for speed against unsalted hashes, and credential stuffing reuses passwords leaked elsewhere. Each is defeated by a specific control, and the arithmetic shows why length matters most.

In examination wording: password cracking is the recovery of passwords from stored data or by repeated guessing; the principal methods are dictionary attacks, brute-force attacks, hybrid attacks, rainbow-table attacks against unsalted hashes, and credential stuffing exploiting reuse; the feasibility of brute force is governed by the size of the keyspace, which grows exponentially with password length.

Online against offline: the distinction that decides everything

Before the methods, the single most important distinction, because it determines which defence matters.

Online attacks guess at a live login. Every attempt goes through the system, which can count them, slow them, and lock the account. The attacker is limited to a handful of guesses before being blocked, so only the very weakest passwords fall, and the defences are rate limiting, lockout and multi-factor authentication.

Offline attacks happen after the attacker has stolen the password store (the previous chapter's scenario). Now there is no live system to count or slow the guesses; the attacker computes hashes on their own hardware, as fast as it allows, limited only by the strength of the hashing and the strength of the passwords. This is where billions of guesses per second happen, and where the storage model (slow, salted) and password strength are the only defences that apply.

The examinable consequence: lockout and rate limiting protect against online attacks and do nothing offline; the storage model and password strength protect against offline attacks. Confusing the two, for example thinking account lockout protects a stolen database, is a common error.

The attack methods

Dictionary attacks. Try likely passwords: common ones, words from a dictionary, names, and, most effectively, lists of passwords leaked from previous breaches. Because human password choice is so predictable, this catches a large fraction of accounts quickly, and leaked-password lists mean the "dictionary" is now tens of millions of passwords real people actually used.

Brute force. Try every possible combination up to some length. Guaranteed to succeed eventually, but "eventually" grows explosively with length, as the arithmetic below shows, so it is practical only against short or weak passwords.

Hybrid attacks. Dictionary words with predictable modifications: a capital first letter, a digit and a symbol appended, common substitutions. These catch exactly the passwords people choose when told to "add a number and a symbol", such as Password1!, which feels complex and is not.

Rainbow-table attacks. Precomputed tables mapping hashes back to passwords, so a stolen unsalted hash is looked up rather than cracked. The expensive computation is done once and reused. Defeated entirely by salting, from the previous chapter, which is why salting is not optional.

munotes.in280

How Passwords Are Attacked, and the Arithmetic of a Keyspace

Credential stuffing. Take username-and-password pairs leaked from one breach and try them, automatically and at scale, on many other services, relying on reuse. This is the most common real attack today, and it is why a password leaked from a trivial site endangers a user's important accounts. It is an online attack in form but uses confirmed credentials, so it succeeds far more often than blind guessing.

The arithmetic of length

"Make passwords longer" is provable, not a slogan. The number of possible passwords is the size of the character set raised to the power of the length. Take a character set of 95 printable characters, and count.

A six-character password has 95 × 95 × 95 × 95 × 95 × 95 = 735091890625 possibilities, about 735 billion. Each extra two characters multiplies that by 95 × 95 = 9025. So an eight-character password has 735091890625 × 9025 = 6634204312890625 possibilities, and a ten-character password has 6634204312890625 × 9025 = 59873693923837890625, close to sixty quintillion.

Length beats complexity: adding two characters multiplies the attacker's work by more than nine thousand, while swapping one letter for a symbol barely changes the count. A twelve-character passphrase of ordinary words is far stronger than an eight-character string of mixed symbols, and far easier to remember, which is why modern guidance favours length over mandated complexity.

The arithmetic also explains the online/offline split quantitatively. Against an online login limited to, say, ten guesses before lockout, even a six-character password is safe from brute force, because 735 billion possibilities against ten guesses is no contest. Against an offline attacker doing billions of guesses per second on a fast unsalted hash, that same six-character password falls in seconds, and only length and slow hashing push it back out of reach. The number that matters is set by which attack applies.

The defences, each matched to a method

Every defence maps to a specific attack, which is the defensive analysis MU asks for:

AttackDefeated by
Brute forceLength (the arithmetic), and a slow hash offline
Dictionary and leaked-listBlocking known-breached and common passwords at the point of choice
HybridLength again; a longer passphrase has no predictable pattern to exploit
Rainbow tablesSalting (previous chapter), completely
Offline cracking generallyA slow, salted hash (previous chapter)
Online guessingRate limiting and account lockout
Credential stuffingUnique passwords per site (a password manager) and multi-factor authentication
Any stolen or guessed passwordMulti-factor authentication, which makes it insufficient alone

The defensive summary in one line: make each guess slow (hashing), make each account hard to hammer (rate limiting, lockout), make the password space huge (length), make reuse harmless (uniqueness), and make a stolen password insufficient (multi-factor).

munotes.in281

How Passwords Are Attacked, and the Arithmetic of a Keyspace

A worked example, framed defensively

A company's password database is stolen. What happens depends entirely on the defender's earlier choices, which is the chapter's point:

  • Stored as fast, unsalted hashes: an attacker uses a rainbow table and recovers most passwords in minutes. Defence that would have prevented it: salting and a slow hash.
  • Stored as a slow, salted hash: offline cracking is reduced to the weakest passwords only, and even those take real time. The storage did its job; now length and blocking common passwords determine how many fall.
  • For accounts with multi-factor authentication: the recovered password alone does not grant access, so the breach's impact is limited regardless of password strength.
  • For users who reused these passwords elsewhere: credential stuffing endangers their other accounts, which uniqueness and multi-factor on those services would limit.

The response ranks the defences by which attack now applies: because this is an offline scenario, lockout is irrelevant and the storage model plus password strength plus multi-factor are what matter, which is exactly the online/offline reasoning applied.

What beginners get wrong

  • Thinking account lockout protects a stolen database. It protects online logins and does nothing offline, where the attacker has the hashes and no live system to lock.
  • Believing mandated complexity is the main defence. It mostly produces predictable Password1! strings that hybrid attacks catch. Length matters far more.
  • Assuming a strong password survives a breach. Once the store is stolen, only the storage model and multi-factor protect it; the password's strength helps only against brute force, not against a fast unsalted hash or a leaked plaintext.
  • Ignoring reuse. The biggest real-world attack is credential stuffing, which strong-but-reused passwords do nothing against. Uniqueness per site is essential.
  • Confusing the online and offline settings. They call for entirely different defences, and naming which one applies is the first step of any analysis.
  • Treating rainbow tables as a current threat against salted stores. Salting defeats them entirely; they matter only where hashes are unsalted.

Quick revision

  • Online attacks guess at a live login and are limited by rate limiting, lockout and multi-factor; only the weakest fall. Offline attacks work on a stolen store at hardware speed, limited only by the hashing and the password strength.
  • Methods: dictionary (likely words and leaked lists), brute force (all combinations, grows with length), hybrid (words with predictable tweaks), rainbow tables (precomputed, against unsalted hashes), credential stuffing (reuse across sites, the commonest today).
  • Length arithmetic (95-character set): six characters 95 × 95 × 95 × 95 × 95 × 95 = 735091890625; each extra two characters multiplies by 95 × 95 = 9025; eight characters 6634204312890625; ten characters 59873693923837890625. Length beats complexity.
  • Defences by attack: length (brute force), block known-bad (dictionary), salting (rainbow tables), slow salted hash (offline), rate limiting and lockout (online), uniqueness and multi-factor (credential stuffing), multi-factor (any stolen password).
munotes.in282

How Passwords Are Attacked, and the Arithmetic of a Keyspace

Test yourself

  1. Distinguish online and offline password attacks, and say which defences apply to each.

Online attacks guess at a live login, which can count, slow and lock the attempts, so they are limited to a few guesses and defeated by rate limiting, account lockout and multi-factor authentication. Offline attacks run against a stolen password store on the attacker's own hardware with no live system to slow them, so they are limited only by the strength of the hashing and of the passwords, and are defeated by a slow, salted hash, strong passwords and multi-factor authentication.

  1. Why does length defeat brute force more effectively than mandated complexity?

Because the number of possibilities is the character-set size raised to the length, so each added character multiplies the attacker's work: for a 95-character set, each extra two characters multiplies the space by 9025. Swapping one character type for another barely changes the count, so a longer passphrase grows the keyspace exponentially while adding a symbol does not.

  1. What is credential stuffing, why is it so effective, and what defeats it?

It is the automated reuse of username-and-password pairs leaked from one breach against many other services. It is effective because it uses confirmed credentials rather than blind guesses and exploits widespread password reuse, so it succeeds far more often than guessing. It is defeated by using a unique password per site, typically via a password manager, and by multi-factor authentication, which makes a reused password insufficient alone.

  1. Once a password database is stolen, which defences still protect the users, and why is lockout not among them?

The storage model, a slow salted hash that makes offline cracking infeasible for strong passwords, and multi-factor authentication, which makes a recovered password insufficient. Account lockout is not among them because it only limits guesses at a live login; an offline attacker has the hashes and computes guesses on their own hardware, where there is nothing to lock.

  1. Why does salting defeat rainbow-table attacks entirely?

Because a rainbow table is precomputed against passwords with no salt, and a per-user random salt means the attacker would have had to build a separate table for each specific salt, which they could not anticipate. The precomputed work is therefore useless, and the attacker is forced back to cracking each salted password individually at full cost.

Contents This chapter on its own page

munotes.in283

Chapter Fifty-Nine

Password Policy, Managers and Multi-Factor Authentication

Syllabus topic Module 1, "Cryptography and Password Security Analysis"; Course Outcome 5, "Recommend appropriate mitigation strategies"

In one line

Good password policy follows from the attack arithmetic: favour length, block known-bad passwords, stop forcing periodic changes and mandated complexity, use a password manager for uniqueness, and above all deploy multi-factor authentication so that a stolen or guessed password is not enough.

In examination wording: effective authentication policy emphasises password length over imposed complexity, screens passwords against known-breached lists, avoids mandatory periodic expiry, supports password managers to enable unique credentials per service, and requires multi-factor authentication using factors from different categories to ensure that compromise of the password alone does not grant access.

Policy follows from the previous chapter

The attack analysis dictates the policy, so each recommendation here is a conclusion from there rather than a preference.

  • Offline attacks are defeated by length and slow salted hashing, so policy should maximise length.
  • Dictionary and leaked-list attacks are defeated by blocking known-bad passwords, so policy should screen at the point of choice.
  • Credential stuffing is defeated by uniqueness, so policy should enable password managers.
  • Any stolen or guessed password is defeated by multi-factor, so policy should require it.

Two long-standing requirements are missing from that list, deliberately, because the evidence turned against them.

The two rules modern guidance reversed

Forced periodic expiry. For decades, policy required users to change their password every 30, 60 or 90 days. Current guidance, including that of major standards bodies, recommends against routine forced expiry, and the reasoning is instructive.

Forcing frequent changes does not improve security and actively harms it, because users respond predictably: they choose a memorable base and append an incrementing number or the month, so Spring2026 becomes Summer2026, which an attacker who has one password can guess. The change is therefore not really a change, and the burden pushes users toward weaker, more patterned passwords and toward writing them down insecurely. Expiry also does nothing about the real risk, which is that a password is compromised and used immediately, long before the next scheduled change.

The modern position: change a password when there is a reason to (evidence of compromise, appearance in a breach), not on a calendar. This frees users to choose one strong password they can remember rather than a series of weak patterned ones.

Mandated complexity. The familiar "at least one uppercase, one lowercase, one digit and one symbol" is also now discouraged as the primary rule, because, as the arithmetic chapter showed, it mostly produces predictable Password1! strings that hybrid attacks catch, while length delivers far more strength. Complexity requirements also frustrate users into predictable patterns and reuse.

The modern position: require a reasonable minimum length and encourage passphrases, screen against known-bad passwords, and do not impose rigid character rules. A long passphrase of ordinary words satisfies security without the patterns complexity rules induce.

munotes.in284

Password Policy, Managers and Multi-Factor Authentication

Stating these two reversals clearly is important because many organisations still enforce the old rules, and a tester recommending modern policy must be able to explain why the intuitive rule is wrong.

What good policy does require

  • A reasonable minimum length, favouring passphrases, because length is what defeats brute force.
  • Screening against known-breached and common passwords at the point of choice, which defeats dictionary and leaked-list attacks directly by refusing the passwords those attacks try.
  • No routine forced expiry; change on evidence of compromise.
  • No rigid complexity mandates; length and screening instead.
  • Support for password managers, and encouragement to use them.
  • Correct storage (the storage chapter): slow, salted hashing.
  • Rate limiting and lockout for online guessing, tuned so that lockout does not itself become a denial-of-service lever against legitimate users.
  • Multi-factor authentication, below.

Password managers

A password manager generates and stores a strong, unique password for every service, so the user need remember only one strong master password (and, ideally, protect the manager itself with multi-factor authentication).

Why it is the practical answer to reuse:

  • It makes uniqueness effortless, which is the only real defence against credential stuffing, because a password leaked from one site is useless elsewhere.
  • It makes length and randomness effortless, since the user does not have to remember the generated passwords.
  • Many managers also check stored passwords against known breaches and warn on reuse.
  • Browser-integrated managers resist phishing as a side effect: the manager fills a password only on the site it was saved for, so a look-alike domain gets nothing, which is a genuine security benefit beyond convenience.

The objection students raise is that it concentrates risk in one place. The response is that the concentration is protected by a strong master password and multi-factor authentication, and that the alternative, remembering many passwords, provably produces reuse and weak choices. The concentrated risk, well protected, is far smaller than the distributed risk of human memory.

Multi-factor authentication

The most effective single control against credential attacks, because it breaks the link between "the attacker has the password" and "the attacker has access".

The factor categories, which the examination asks for:

  • Something you know: a password, a PIN.
  • Something you have: a phone, a hardware token, a security key.
  • Something you are: a fingerprint, a face, other biometrics.

Genuine multi-factor authentication combines factors from different categories. A password plus a security question is two things you know, so an attacker who obtains one by research or phishing likely obtains both; it is not multi-factor.

The methods, ranked by resistance to attack, as the phishing chapter referenced:

munotes.in285

Password Policy, Managers and Multi-Factor Authentication

  • SMS codes: the weakest, vulnerable to SIM-swap attacks and interception, and phishable, but far better than nothing.
  • Authenticator application codes: better, with no telephone network to attack, but still phishable in real time: an attacker relaying the login can ask the victim for the current code and use it within its short validity.
  • Push approval: convenient, and vulnerable to fatigue attacks, where repeated prompts are sent until an irritated user approves one; number matching, requiring the user to type a number shown on the login screen, largely fixes this and should be enabled.
  • Phishing-resistant factors (security keys and platform authenticators using the modern standards): the strongest, because the credential is cryptographically bound to the legitimate site, so it produces no valid response to a look-alike domain and defeats even a real-time relay.

Where to require it: everywhere that matters, and specifically on the paths attackers use, remote access and VPN, email, administrative accounts, cloud consoles, and anything holding personal or financial data. An organisation that enables it for ordinary staff and exempts executives, who are the whaling targets, has protected the wrong people.

The recovery path, the lesson from the social-engineering case: securing the login and leaving a weak reset route relocates the attack. The procedure to reset or re-enrol a factor must be at least as strong as the factor it restores, or it becomes the way in.

A worked example

A tester reviews an organisation's authentication policy and recommends changes ranked by effect.

  • The policy forces a password change every 60 days and mandates complexity. Recommendation: remove both, because they produce patterned passwords and reuse; require a longer minimum and screen against breached lists instead.
  • Passwords are not screened against known-breached lists. Recommendation: add screening at the point of choice, defeating dictionary and leaked-list attacks directly.
  • Multi-factor is enabled for staff but not for executives or administrators. Recommendation, high priority: extend it to exactly those accounts, which are the highest-value targets.
  • The multi-factor method is SMS. Recommendation: move to authenticator apps at least, and to security keys for administrators and finance, since SMS is the weakest and phishable.
  • Password managers are blocked by policy "for security". Recommendation, and a common mistake to correct: permit and encourage them, because they are the only practical route to unique passwords per site.

The report explains each reversal, because the old rules are intuitive and the recommendations will be questioned by anyone who learned the previous generation of advice.

What beginners get wrong

  • Recommending forced periodic expiry. Modern guidance advises against it: it produces patterned incrementing passwords and does nothing about immediate compromise. Change on evidence, not on a calendar.
  • Treating mandated complexity as the main control. It produces predictable Password1! strings; length and screening deliver far more.
  • Blocking password managers "for security". They are the practical answer to reuse and add phishing resistance; blocking them forces reuse and weak choices.
  • Calling a password plus a security question multi-factor. Both are things you know.
  • Assuming all second factors are equal. SMS is weakest; app codes are phishable in real time; push needs number matching; only site-bound keys resist phishing.
  • Securing the login and not the reset path. The recovery procedure must be as strong as the factor it restores.
  • Exempting executives and administrators from multi-factor. They are the highest-value targets and must be covered first.
munotes.in286

Password Policy, Managers and Multi-Factor Authentication

Quick revision

  • Policy follows the attack arithmetic: favour length, screen against known-bad passwords, no forced periodic expiry (change on evidence, since expiry produces patterned passwords), no rigid complexity mandates, support password managers, correct storage, and rate limiting and lockout for online guessing.
  • Password managers make uniqueness and randomness effortless, defeating credential stuffing, and resist phishing by filling only on the saved site; the concentrated risk is protected by a strong master password and multi-factor.
  • Multi-factor: factors from different categories, know / have / are. A password plus a security question is two things you know, so not multi-factor.
  • Method ranking: SMS (weakest, phishable, SIM-swap) < app codes (phishable in real time) < push (needs number matching against fatigue) < phishing-resistant keys (site-bound, defeat real-time relay).
  • Apply to remote access, email, administrative and executive accounts, and sensitive data; secure the reset path to the same strength as the factor.

Test yourself

  1. Why does modern guidance advise against forced periodic password expiry?

Because forcing frequent changes produces predictable behaviour: users choose a memorable base and append an incrementing number or the month, so the change is not a genuine change and is guessable from one known password, and the burden drives users toward weaker, more patterned passwords and insecure storage. Expiry also does nothing about the real risk, which is a password being compromised and used immediately, so the recommendation is to change on evidence of compromise rather than on a schedule.

  1. Why is mandated character complexity discouraged as the primary rule, and what replaces it?

Because it mostly produces predictable strings such as Password1! that hybrid attacks catch, while adding far less strength than length does, and it frustrates users into patterns and reuse. It is replaced by a reasonable minimum length with a preference for passphrases, together with screening against known-breached and common passwords.

  1. Why is blocking password managers a mistake?

Because password managers are the only practical way for users to have a strong, unique password for every service, which is the sole real defence against credential stuffing, and they additionally resist phishing by filling credentials only on the site they were saved for. Blocking them forces users back onto memory, which reliably produces reuse and weak passwords, so the concentrated but well-protected risk of a manager is far smaller than the distributed risk it removes.

munotes.in287

Password Policy, Managers and Multi-Factor Authentication

  1. What defines genuine multi-factor authentication, and why is a password plus a security question not multi-factor?

It combines factors from different categories: something you know, something you have, and something you are. A password and a security question are both things you know, so an attacker who obtains one through research or phishing is likely to obtain the other by the same means, providing none of the independence that multi-factor authentication is meant to give.

  1. Rank the common second-factor methods by resistance to phishing, and explain why the strongest resists a real-time relay.

SMS is weakest, being vulnerable to SIM-swap, interception and phishing; authenticator application codes are better but still phishable through a real-time relay; push approval is vulnerable to fatigue attacks unless number matching is enabled; security keys and platform authenticators are strongest. The strongest resist a real-time relay because the credential is cryptographically bound to the legitimate site's identity, so it produces no valid response when presented with a look-alike domain, which is exactly what a relaying attacker controls.

Contents This chapter on its own page

munotes.in288

Chapter Sixty

Cryptographic Weaknesses to Know

Syllabus topic Module 1, "Cryptography and Password Security Analysis: ... cryptographic weaknesses"

In one line

Real cryptographic failures are almost never a broken cipher. They are a sound cipher used wrongly: the wrong algorithm for the job, a fast hash for passwords, a missing salt, a hard-coded key, weak randomness, or a home-made scheme. Knowing the small set of recurring mistakes is what a defender and a tester need.

In examination wording: cryptographic weaknesses in practice arise predominantly from misuse rather than from breaks in the underlying primitives, including the use of obsolete or inappropriate algorithms, inadequate key management, insufficient randomness, absence of salting or of authenticated encryption, and the deployment of unvetted custom schemes.

The organising insight

Students imagine cryptographic weakness as brilliant mathematicians breaking ciphers. That happens rarely and slowly. The failures a tester finds, week after week, are of a different and duller kind: a strong, standard, unbroken algorithm applied in a way that undoes its strength.

This is good news for a defender, because it means the fixes are known and mechanical rather than requiring cryptographic research. It is also the reason the block insisted on distinctions, encoding against encryption against hashing, fast against slow hashes, salted against unsalted: nearly every weakness below is one of those distinctions ignored.

So the chapter is a catalogue of misuse, grouped, each with what to use instead.

Weaknesses in choosing the primitive

Using an obsolete algorithm. MD5 and SHA-1 for anything relying on collision resistance (signatures, certificates); DES for encryption, its key far too short for modern hardware; RC4 as a stream cipher, with known biases; older TLS and SSL versions. These are broken or weakened and current replacements exist: SHA-256 or SHA-3 for hashing, AES for encryption, TLS 1.2 or 1.3 for transport. The finding is "obsolete algorithm in use"; the fix is the current standard.

Using a fast hash for passwords. SHA-256 is not broken, but it is fast, and fast is wrong for passwords, as the storage chapter established. A very common real finding is passwords stored with a general-purpose hash rather than a purpose-built slow one. Fix: bcrypt, scrypt or Argon2.

Using encryption where hashing is required, or the reverse. Encrypting passwords (reversible, so a stolen key exposes them) is the classic case; using a plain hash where authenticated encryption is needed is another. Fix: match the tool to the job, per the first chapter of the block.

Using encoding as if it were encryption. Base64 or similar treated as protection. No key, reversible by anyone, no security. Fix: actually encrypt or hash.

Weaknesses in how the primitive is used

No salt, or a shared salt. Unsalted password hashes enable rainbow tables and expose shared passwords; a single salt reused for all users restores both problems for that salt. Fix: a unique random salt per password.

munotes.in289

Cryptographic Weaknesses to Know

Weak or predictable randomness. Cryptography depends on unpredictable values: keys, salts, initialisation vectors, session tokens, nonces. Generating them with an ordinary (non-cryptographic) random source, or from a predictable seed such as the current time, makes them guessable, which undoes the cryptography built on them. This connects to the session-token prediction of Module 2: a token is only as unguessable as the randomness that made it. Fix: use the platform's cryptographically secure random source for anything security-relevant.

Reused initialisation vectors or nonces. Many encryption modes require a value that must be unique (and sometimes unpredictable) for each use; reusing it can leak information about the plaintext or, in some modes, be catastrophic. Fix: follow the mode's rules, generate the value correctly, never reuse it with the same key.

Encryption without integrity. Encrypting data so it is confidential while doing nothing to detect tampering allows an attacker to alter ciphertext in ways that change the plaintext meaningfully without being detected. Modern practice uses authenticated encryption, which provides confidentiality and integrity together. Fix: use an authenticated mode rather than encryption alone.

Insufficient key length. A sound algorithm with too short a key is weak; standards specify minimum lengths (for example RSA keys below 2048 bits are considered inadequate). Fix: use current recommended key sizes.

Weaknesses in key management

Key management is where much real cryptographic failure lives, because the algorithms are fine and the keys are mishandled.

Hard-coded keys. A key embedded in source code, in a configuration file in the repository, or in a compiled application. Anyone who reads the code or the file has the key, and the code is often in a public repository (the committed-secret finding from the reconnaissance chapter). Fix: keys in a secret-management system, never in code.

Keys stored with the data they protect. Encrypting a database and storing the key in the same database, or on the same server with the same access controls, means one breach yields both. This is the flaw that makes encrypting passwords pointless. Fix: separate the key from the data, ideally in a dedicated key-management service or hardware module.

No key rotation. A key used indefinitely means a single compromise, whenever it occurs, exposes everything ever protected with it. Fix: rotate keys on a schedule and on suspected compromise, and design so rotation is possible.

Keys shared too widely. A key distributed to every machine or every developer is a key that will leak. Fix: least privilege for keys, as for everything else.

The one that is a category of its own: rolling your own

Home-made cryptography. Designing a custom cipher, a custom protocol, or a custom "obfuscation" scheme, in the belief that secrecy of the method adds security. It is almost always weaker than a standard, for reasons the encryption chapter gave: security should rest on the key with the method assumed public, and standard algorithms are secure precisely because they have been attacked by experts for years without breaking. A custom scheme has had no such scrutiny.

munotes.in290

Cryptographic Weaknesses to Know

The rule, which examiners like as a flat statement: do not invent cryptography; use vetted, standard implementations. This extends to not implementing even a standard algorithm yourself where a reviewed library exists, because implementation mistakes (timing side channels, incorrect padding handling) are themselves a rich source of weakness.

A worked example

A tester reviews an application's use of cryptography and reports each finding with its category and fix.

FindingCategoryFix
Passwords stored as unsalted MD5Obsolete algorithm, fast hash, no saltSalted bcrypt or Argon2
Session tokens generated from the current timeWeak randomnessCryptographically secure random source
The database encryption key is in a configuration file in the code repositoryHard-coded key; key stored with access to the dataSecret-management system, key separated from data
Data encrypted but not authenticated, and a parameter's ciphertext can be alteredEncryption without integrityAuthenticated encryption
A custom "encryption" that is actually a fixed substitutionHome-made cryptography; effectively encodingA standard cipher; and understand it provides no security as built
TLS 1.0 still enabledObsolete protocol versionRequire TLS 1.2 or 1.3

Not one of these is a broken algorithm in the mathematical sense; every one is a standard tool used wrongly or an obsolete tool retained, which is the chapter's thesis demonstrated.

What beginners get wrong

  • Imagining cryptographic weakness means broken ciphers. Almost all real findings are misuse: wrong algorithm, wrong parameters, bad key management, or home-made schemes.
  • Using a fast unbroken hash for passwords. SHA-256 is not broken and is still wrong for passwords because it is fast; use a slow purpose-built hash.
  • Trusting weak randomness. Keys, salts, tokens and nonces from a non-cryptographic or predictable source undo the cryptography built on them.
  • Encrypting without integrity. Confidentiality without tamper-detection lets an attacker alter ciphertext; use authenticated encryption.
  • Hard-coding keys or storing them with the data. One breach then yields both; separate the key and keep it out of code.
  • Rolling your own cryptography. Unvetted schemes are almost always weaker than standards; use reviewed implementations and do not implement primitives yourself.
  • Reporting encoding as encryption. No key, reversible by anyone, no security.

Quick revision

  • The insight: real cryptographic weakness is almost always a sound primitive used wrongly, not a broken cipher.
  • Choosing the primitive: obsolete algorithms (MD5, SHA-1 for collision-dependent uses, DES, RC4, old TLS) replaced by current standards; a fast hash for passwords replaced by a slow one; encryption where hashing is needed or the reverse; encoding treated as encryption.
  • Using it: no salt or shared salt; weak or predictable randomness for keys, salts, tokens, nonces; reused IVs or nonces; encryption without integrity (use authenticated encryption); insufficient key length.
  • Key management: hard-coded keys, keys stored with the data, no rotation, keys shared too widely.
  • Do not invent cryptography; use vetted standard implementations, and do not implement primitives yourself where a reviewed library exists.
munotes.in291

Cryptographic Weaknesses to Know

Test yourself

  1. What is the organising insight of this chapter, and why does it matter for defence?

That real cryptographic weaknesses are overwhelmingly cases of a sound, standard, unbroken algorithm used incorrectly rather than a cipher being mathematically broken. It matters because it means the fixes are known and mechanical, matching the tool to the job and following its rules, rather than requiring cryptographic research, so a defender can address the whole class through the distinctions the block established.

  1. Give three examples of a sound primitive used wrongly, with the fix for each.

Storing passwords with a fast hash such as SHA-256, fixed by using a slow purpose-built hash like bcrypt or Argon2; generating session tokens or keys from a predictable source such as the current time, fixed by using a cryptographically secure random source; and encrypting data without integrity protection, fixed by using authenticated encryption that provides confidentiality and tamper-detection together.

  1. Why is weak randomness a cryptographic weakness even when the algorithm is sound?

Because cryptography depends on unpredictable values, keys, salts, initialisation vectors, session tokens and nonces, and if these are produced by a non-cryptographic generator or from a predictable seed, they can be guessed, which undermines everything built on them regardless of the strength of the algorithm. A session token, for example, is only as unguessable as the randomness that produced it.

  1. What are the principal key-management failures, and what do they have in common?

Hard-coded keys embedded in code or configuration, keys stored alongside the data they protect, keys that are never rotated, and keys shared too widely. They have in common that the algorithm is sound while the key is mishandled, so an attacker obtains the key without breaking any cryptography, which is why key management is where much real cryptographic failure lives.

  1. Why is home-made cryptography discouraged, and how far does the rule extend?

Because security should rest on the secrecy of the key with the method assumed public, and standard algorithms are trusted precisely because they have withstood years of expert attack, scrutiny a custom scheme has not had, so custom schemes are almost always weaker. The rule extends to not implementing even standard algorithms oneself where a reviewed library exists, because implementation mistakes such as timing side channels and incorrect padding handling are themselves a significant source of weakness.

Contents This chapter on its own page

munotes.in292

Chapter Sixty-One

Hubs, Switches, and Passive Sniffing

Syllabus topic Module 1, "Network Sniffing and Man-in-the-Middle Attacks: Study packet sniffing techniques ... and countermeasures to secure network communication"

In one line

On an old network built with a hub, every machine could read everyone's traffic, so sniffing was trivial. Modern networks use a switch, which sends each frame only to the port it is for, so a machine normally sees only its own traffic. Everything in this block is a way to defeat that, and every defeat has a defence.

In examination wording: packet sniffing is the capture of network traffic for inspection; on a shared medium such as a hub-based network all traffic is visible to every host, whereas a switch forwards frames only to the port associated with the destination's hardware address, so an attacker on a switched network must actively subvert the switch's forwarding to observe traffic not addressed to them.

Why the medium decides everything

To understand the whole block, you need one fact about how local networks deliver frames, and it explains why sniffing was once easy and is now hard.

Every network interface has a MAC address, a hardware address unique to that card. When one machine sends a frame to another on the same local network, the frame carries the destination's MAC address, and the delivery device decides who actually receives it.

  • A hub is a simple repeater: it sends every frame it receives out of every port. So every machine on a hub receives every frame, and any machine can read all of it by simply choosing to. Hubs made sniffing effortless, and they are why older network attacks assumed a shared medium.
  • A switch is smarter: it learns which MAC address is on which port, by watching the source addresses of frames, and builds a table (the MAC address table, or CAM table). Thereafter it sends each frame only out of the one port where its destination lives. So on a switch, your machine receives only frames addressed to it, plus broadcasts.

The consequence is the premise of the block: on a switched network, a machine cannot passively read others' traffic, because the switch never sends it to them. To sniff, an attacker must make the switch misbehave, and the three ways of doing that, MAC flooding, ARP poisoning and DNS spoofing, are the next three chapters, each defeating the switch differently and each stopped by a specific control.

Promiscuous mode

A related concept a student should know. Normally a network card ignores frames not addressed to it, even any that happen to arrive. Promiscuous mode tells the card to accept and pass up all frames it receives, which is what a sniffer needs.

On a hub, promiscuous mode alone was enough to read everything, because everything arrived. On a switch, promiscuous mode is necessary but not sufficient: the card will now accept anything it receives, but the switch still only sends it the frames for its own port, so there is nothing extra to accept until the switch is subverted. That is the precise sense in which a switch changed the game: it did not stop a machine listening, it stopped the traffic arriving.

munotes.in293

Hubs, Switches, and Passive Sniffing

A legitimate use worth noting, because it is also the defensive one: a network monitoring or intrusion-detection sensor is deliberately fed a copy of all traffic, through a mirror port on the switch or a network tap, and runs in promiscuous mode to inspect it. The same capability that an attacker abuses is how a defender watches their own network, which is why the countermeasures chapter can rely on the defender seeing traffic the attacker is trying to.

What a capture actually reveals

Suppose an attacker does defeat the switch and capture traffic. What do they get? The answer depends entirely on whether the traffic is encrypted, and it is the thread that runs to the countermeasures chapter.

Unencrypted traffic is fully readable: the contents of pages, the text of messages, and, most seriously, credentials sent by protocols that do not encrypt, such as older mail and file-transfer protocols and any web login not protected by TLS. A capture of an unencrypted login is the password, in the clear. This is why protocols that send credentials without encryption are a serious finding regardless of anything else.

Encrypted traffic yields only ciphertext for its contents. The attacker sees that two parties are communicating, how much and when, and the unencrypted envelope information (addresses, and often the destination host name during connection setup), but not the contents. This residual information is called metadata, and it can be revealing in aggregate, but the contents, the passwords, the messages, the data, stay protected.

The lesson, which the countermeasures chapter makes the centre of its argument: encryption in transit accepts that traffic might be captured and makes the capture nearly worthless. So the deepest defence against sniffing is not to prevent the capture, which the rest of the block shows is hard to guarantee, but to ensure that a capture reveals only ciphertext.

The legal and ethical line

Capturing traffic that is not addressed to you is reading other people's communications, and it is an act under section 43, engaging the interception provisions of the law as well. It is done only on a network you own or are explicitly authorised to test, and even then a professional captures the minimum needed to demonstrate a finding, extracts and reports the relevant fact (for example "credentials for this protocol are sent unencrypted"), and does not retain or read others' actual communications beyond that. The reader-stamp and confidentiality disciplines from earlier chapters apply: what is seen is handled as sensitive and minimised in the report.

munotes.in294

Hubs, Switches, and Passive Sniffing

A worked example, run as a defender

An assessor evaluates whether an office network protects traffic from a local eavesdropper, testing on the client's own network with authorisation.

  • The network is switched, so a machine plugged into a port sees, by default, only its own traffic and broadcasts. Passive sniffing alone reveals little, which is the switch doing its job.
  • To test what an attacker who defeated the switch would obtain, the assessor examines the protocols in use rather than capturing colleagues' traffic. They find that an internal application sends login credentials over an unencrypted protocol. Finding: were the switch subverted, these credentials would be captured in the clear.
  • Other services use TLS, so even a successful capture would yield only ciphertext for their contents. Recorded as the correct posture.
  • The assessor confirms the network has a monitoring sensor on a mirror port, which is the legitimate promiscuous-mode use, and notes it as a positive control that would help detect the switch-subversion attacks of the next chapters.

The report's recommendations point forward: move the unencrypted application to an encrypted protocol (the durable fix, since it makes any capture worthless), and ensure the switch controls of the countermeasures chapter are in place to make subversion hard. Note that the assessor established the risk by examining protocols, not by capturing anyone's communications, which is the ethical discipline in practice.

What beginners get wrong

  • Thinking a switch makes sniffing impossible. It makes passive sniffing of others' traffic impossible; the next three chapters defeat it. The durable defence is encryption, not the switch.
  • Confusing promiscuous mode with the ability to capture. Promiscuous mode makes the card accept all frames it receives; on a switch, the switch still does not send others' frames to it, so there is nothing extra to accept until it is subverted.
  • Believing a capture always reveals contents. Only unencrypted traffic is readable; encrypted traffic yields metadata (who, when, how much) but not contents.
  • Underrating unencrypted protocols. A capture of an unencrypted login is the password in the clear; such protocols are a serious finding.
  • Forgetting that monitoring uses the same capability. A defender's sensor runs in promiscuous mode on a mirror port; the capability an attacker abuses is how the network is watched.
  • Capturing colleagues' traffic to prove a point. The risk is established by examining protocols; actual communications are minimised and handled as sensitive.

Quick revision

  • Every interface has a MAC address. A hub repeats every frame to every port (sniffing trivial); a switch learns which MAC is on which port and sends each frame only there (a machine sees only its own traffic plus broadcasts).
  • So on a switched network, passive sniffing of others' traffic is not possible; the block's next three chapters (MAC flooding, ARP poisoning, DNS spoofing) each defeat the switch, and each has a specific countermeasure.
  • Promiscuous mode makes a card accept all frames it receives; necessary but not sufficient on a switch, and the same capability a monitoring sensor uses legitimately on a mirror port.
  • A capture reveals contents only if the traffic is unencrypted; encrypted traffic yields metadata (who, when, how much) but not contents. Unencrypted credentials are a serious finding.
  • The deepest defence is encryption in transit, which makes any capture nearly worthless; sniffing is an act under s.43 and is done only where authorised, capturing the minimum.
munotes.in295

Hubs, Switches, and Passive Sniffing

Test yourself

  1. Why was sniffing trivial on a hub-based network and difficult on a switched one?

A hub repeats every frame out of every port, so every machine receives all traffic and can read it simply by choosing to. A switch learns which MAC address is on which port and forwards each frame only to that one port, so a machine receives only frames addressed to it plus broadcasts, and therefore cannot passively read others' traffic.

  1. What is promiscuous mode, and why is it necessary but not sufficient to sniff on a switch?

It is a setting that makes a network card accept and pass up all frames it receives rather than only those addressed to it. On a switch it is necessary because a sniffer must accept whatever arrives, but it is not sufficient because the switch still forwards only the frames for that machine's own port, so nothing extra arrives to be accepted until the switch's forwarding is subverted.

  1. What does a captured stream reveal when the traffic is encrypted, and what when it is not?

Unencrypted traffic is fully readable, including page contents, messages and any credentials sent by protocols without encryption, so a captured unencrypted login is the password in the clear. Encrypted traffic yields only ciphertext for its contents, leaving metadata such as who is communicating, when, how much, and often the destination host name, but not the contents.

  1. Why is encryption in transit described as the deepest defence against sniffing?

Because the rest of the block shows that preventing a capture on a switched network cannot be fully guaranteed, since the switch can be subverted in several ways. Encryption accepts that a capture may occur and makes it nearly worthless, since the attacker obtains only ciphertext for the contents, so it defends the data regardless of whether the capture succeeds.

munotes.in296

Hubs, Switches, and Passive Sniffing

  1. How does an ethical assessor establish sniffing risk without violating others' communications?

By examining which protocols are in use and whether they encrypt, rather than capturing colleagues' actual traffic, so that a finding such as "credentials for this protocol are sent unencrypted" can be reported from the protocol's properties. Where any capture is needed it is done only on an authorised network, minimised to what demonstrates the finding, and handled as sensitive.

Contents This chapter on its own page

munotes.in297

Chapter Sixty-Two

MAC Flooding

Syllabus topic Module 1, "Network Sniffing and Man-in-the-Middle Attacks: ... MAC flooding ... and countermeasures"

In one line

A switch's address table has a limited size. MAC flooding fills it with fake entries, and many switches, unable to record where a real address belongs, fall back to sending traffic to every port, like a hub, so an attacker can read it. The fix is one switch feature: port security.

In examination wording: MAC flooding is an attack that overwhelms a switch's finite MAC address table with a large number of frames bearing forged source addresses; when the table is exhausted, some switches fail open and broadcast frames for which they have no table entry to all ports, restoring the shared-medium behaviour of a hub and permitting sniffing.

The mechanism

The previous chapter said a switch learns which MAC address is on which port by watching the source addresses of the frames it receives, and stores those mappings in a table. That table is the key to the attack, and to its defence, so understand it precisely.

The table is finite: a switch has room for a certain number of MAC-to-port mappings, and no more. Under normal operation this is ample, because a network has far fewer machines than the table can hold.

MAC flooding abuses the learning mechanism. The attack sends a flood of frames with many different forged source MAC addresses, each of which the switch dutifully learns and records, because learning from source addresses is exactly what it is built to do. Very quickly the table fills up with these fake entries.

Now the switch faces a full table and a frame for a real destination it can no longer find room to have recorded. What it does next depends on the switch, and the dangerous behaviour is the common one: it fails open, meaning that for any destination not in its table it falls back to sending the frame out of every port, exactly as a hub would. The switch has, in effect, been turned back into a hub, and every machine now receives everyone's traffic, which the attacker (in promiscuous mode) reads.

Two things to note. First, this is noisy: a flood of thousands of new MAC addresses in a short time is a conspicuous event, quite unlike normal traffic. Second, it is indiscriminate: it degrades the switch for everyone, so it is disruptive as well as a sniffing method, and a switch that fails open under it is also easier to overload.

Why not every switch fails open

An honest qualification. Not all switches fail open under table exhaustion; some fail closed, dropping frames for destinations they cannot record rather than broadcasting them, which turns the attack into a denial of service (legitimate traffic is dropped) rather than a sniffing opportunity. And managed switches with the countermeasure below do not reach the failure state at all.

munotes.in298

MAC Flooding

So MAC flooding is most effective against older or unmanaged switches that fail open, and its relevance today is partly historical and partly a reminder that unmanaged switches on a network are a weakness. It remains examinable and it remains the clearest illustration of the "defeat the switch" idea, which is why it opens the trio.

The countermeasure: port security

The defence is a single, widely available switch feature called port security, and understanding the mechanism makes the control obvious.

Port security limits the number of MAC addresses a switch will learn on each port, and defines what to do when that limit is exceeded. A normal access port connects to one machine, or a small known number, so it should never see dozens of different source addresses. Configuring the port to accept only a small number, and to shut the port down or drop the excess when more appear, means the flood cannot fill the table: the attacking port hits its limit almost immediately and is disabled or ignored, and the flood never reaches the switch-wide table.

Additional switch controls that harden this further:

  • Sticky or static MAC bindings, tying a port to the specific address expected on it, so an unexpected address is rejected outright.
  • Disabling unused ports, so there is no open socket to plug a flooding device into.
  • Storm control, which caps the rate of broadcast and unknown-destination traffic, limiting the effect even if a table were exhausted.

Because port security is a standard feature of managed switches, the practical recommendation is straightforward: use managed switches, enable port security on access ports, and do not have unmanaged switches on the network. And, as always in this block, encrypt traffic in transit, so that even a switch that somehow failed open would leak only ciphertext, which is the countermeasures chapter's universal point applied here.

A worked example, run as a defender

An assessor reviews a client's switching, with authorisation.

  • The access-layer switches are managed and have port security enabled, limiting each access port to a small number of MAC addresses and shutting a port that exceeds it. A flooding attempt against such a port would disable that port at once and never fill the table. Recorded as the correct posture.
  • One area uses a small unmanaged switch under a desk, added for convenience. It has no port security and, being older, would fail open under flooding. Finding: an unmanaged switch is a weak point that could be turned into a hub.
  • Sensitive internal applications use TLS, so even a successful flood would expose only ciphertext for their contents. Recorded as defence in depth.
munotes.in299

MAC Flooding

Recommendations: replace the unmanaged switch with a managed one and enable port security; disable unused ports; and, as the durable control, ensure applications encrypt in transit so that no switch failure exposes contents. The assessor establishes the risk by inspecting configuration, not by flooding the live network, which would be disruptive and is unnecessary to make the finding.

What beginners get wrong

  • Thinking MAC flooding breaks the switch cleverly. It simply overflows a finite table by abusing the normal learning mechanism; the effect is to make the switch behave like a hub.
  • Assuming every switch fails open. Some fail closed, turning the attack into a denial of service; managed switches with port security do not reach the failure state.
  • Believing it is stealthy. A flood of thousands of new MAC addresses is conspicuous and disruptive.
  • Forgetting unmanaged switches. They are the switches without the countermeasure, and they are where this attack still works.
  • Relying on the switch alone. The durable defence is encryption in transit, so that a switch failing open leaks only ciphertext.

Quick revision

  • A switch learns MAC-to-port mappings into a finite table. MAC flooding sends many frames with forged source MACs, filling the table.
  • Many switches then fail open, broadcasting frames for unknown destinations to every port, behaving like a hub and permitting sniffing; some fail closed (a denial of service instead). Most effective against older or unmanaged switches.
  • It is noisy and disruptive, degrading the switch for everyone.
  • Countermeasure: port security, limiting the number of MAC addresses per port and shutting or restricting a port that exceeds it, so the flood cannot fill the table. Plus static/sticky MAC bindings, disabling unused ports, storm control, and managed switches only.
  • As always, encrypt in transit so a switch failing open leaks only ciphertext.

Test yourself

  1. Explain the mechanism of MAC flooding.

A switch learns which MAC address is on which port by recording the source addresses of incoming frames into a finite table. MAC flooding sends a large number of frames with different forged source MAC addresses, each of which the switch records, quickly exhausting the table. With the table full, the switch can no longer record where real destinations are, and many switches then fail open, broadcasting frames for unknown destinations to every port like a hub, which permits sniffing.

  1. Why does MAC flooding not work equally against all switches?

Because switches differ in how they behave when the table is exhausted: some fail open and broadcast, which enables sniffing, while others fail closed and drop frames they cannot record, which produces a denial of service rather than a sniffing opportunity. Managed switches with port security do not reach the exhaustion state at all, so the attack is most effective against older or unmanaged switches that fail open.

munotes.in300

MAC Flooding

  1. What is port security, and how does it stop MAC flooding?

Port security is a switch feature that limits the number of MAC addresses learned on each port and specifies an action, such as shutting the port or dropping the excess, when the limit is exceeded. Because a normal access port connects to only one or a few machines, the flood's many forged addresses immediately breach the limit on the attacking port, which is disabled or ignored, so the forged entries never fill the switch-wide table.

  1. Why is MAC flooding considered disruptive as well as a sniffing method?

Because it is indiscriminate: filling the table degrades forwarding for every machine on the switch, and a switch that fails open by broadcasting all unknown-destination traffic loses the efficiency that a switch provides, so the attack harms availability for everyone, not only the intended eavesdropping target.

  1. Why does encryption in transit remain relevant even where port security is deployed?

Because it is the defence in depth that makes any switch failure harmless: if a switch were somehow made to fail open despite the controls, encrypted traffic would still expose only ciphertext for its contents, so the durable protection of the data does not depend solely on the switch configuration being correct.

Contents This chapter on its own page

munotes.in301

Chapter Sixty-Three

ARP Poisoning and the Man in the Middle

Syllabus topic Module 1, "Network Sniffing and Man-in-the-Middle Attacks: ... ARP poisoning ... and countermeasures"

In one line

To send an IP packet to another machine on the local network, a computer must first learn that machine's MAC address, which it does with ARP, a protocol that has no authentication. ARP poisoning exploits that: the attacker sends forged ARP replies so that traffic between two parties is sent to the attacker instead, who reads and relays it. It is defeated by switch controls and, decisively, by encryption.

In examination wording: the Address Resolution Protocol maps an IP address to a MAC address on a local network; because hosts accept ARP replies without authentication, an attacker can send forged replies associating their own MAC address with another host's IP address, causing traffic destined for that host to be delivered to the attacker, who forwards it, establishing a man-in-the-middle position.

What ARP is for

IP addresses and MAC addresses are two different things, met in the TCP/IP chapter: an IP address identifies a host across networks, and a MAC address identifies a network card on the local segment. To deliver a packet to a machine on the same local network, the sender needs the destination's MAC address, because local delivery uses MAC addresses, but the sender usually knows only the IP address.

ARP bridges the two. When a machine wants to send to an IP address on its local network and does not know the corresponding MAC address, it broadcasts an ARP request: "who has this IP address?" The machine that owns that IP address replies, "I do, at this MAC address." The sender records the mapping in its ARP cache and uses it, so it does not have to ask again for a while.

This is essential and constant: every local conversation begins with ARP, and the ARP cache is the table of IP-to-MAC mappings each machine keeps.

The design decision that enables the attack

ARP was designed for a small, trusted network, and it has a property that is the root of everything in this chapter: there is no authentication.

Specifically:

  • A machine believes any ARP reply it receives, and records the mapping, even a reply to a request it never sent (a "gratuitous" or unsolicited reply). There is no check that the reply is genuine or that the responder is really the owner of that IP address.
  • A later reply overwrites an earlier one, so whoever answers most recently wins.

So any machine on the local network can tell any other machine that a given IP address is at any MAC address it chooses, and the recipient will believe it. That is not a flaw in an implementation; it is how the protocol was defined, which is why the countermeasures are additional controls layered on top rather than a patch to ARP itself.

munotes.in302

ARP Poisoning and the Man in the Middle

How ARP poisoning works

The attacker exploits the lack of authentication to insert themselves between two parties, typically a victim and the network's gateway (the router to the rest of the world), because most interesting traffic flows through the gateway.

Conceptually, the attacker sends forged ARP replies:

  • to the victim, claiming that the gateway's IP address is at the attacker's MAC address;
  • to the gateway, claiming that the victim's IP address is at the attacker's MAC address.

Both the victim and the gateway update their ARP caches with these false mappings (their caches are now poisoned), and as a result:

  • traffic the victim sends toward the gateway is delivered to the attacker instead;
  • traffic the gateway sends toward the victim is delivered to the attacker instead.

The attacker now sits in the middle. To keep the connection working so the victim notices nothing, the attacker forwards each packet on to its real destination after reading it. This is the man-in-the-middle position: the attacker sees, and can alter, everything passing between the two parties, while both believe they are talking directly to each other.

Because it works at the local-network level and does not depend on the switch's forwarding table, ARP poisoning defeats the switch where the previous chapter's MAC flooding might not: the switch is delivering frames correctly to the attacker's port, because as far as it knows the attacker's MAC legitimately holds that traffic. That is why ARP poisoning is the more reliable and more important of the two.

What the attacker gains, and the crucial limit

The man-in-the-middle position is powerful, and its limit is the most important point in the block.

What it gains: the attacker sees all traffic between the two parties and can modify it in transit, not only read it, which is why a man-in-the-middle threatens integrity as well as confidentiality.

The crucial limit: ARP poisoning diverts traffic; it does not decrypt it. If the traffic is encrypted end to end, the attacker relays ciphertext they cannot read, and cannot usefully alter, because tampering with authenticated ciphertext is detected. So:

  • Unencrypted traffic is fully exposed and alterable.
  • Encrypted traffic (HTTPS, a VPN, SSH) is diverted but stays confidential and integrity-protected, and any attempt to impersonate the far end fails the certificate check, because the attacker cannot present a valid certificate for the real name.

This is the distinction the countermeasures chapter builds its argument on: being in the middle is not the same as being able to read the middle. An attacker who successfully poisons ARP against a victim using HTTPS everywhere obtains diverted ciphertext and a browser certificate warning on any impersonation attempt, which is very different from the plaintext they would get from an unencrypted connection.

munotes.in303

ARP Poisoning and the Man in the Middle

The countermeasures

The defences divide into stopping the poisoning and neutralising its value.

Stopping or detecting the poisoning:

  • Dynamic ARP Inspection, a managed-switch feature that checks ARP replies against a trusted database of legitimate IP-to-MAC bindings (built from the switch's knowledge of which addresses are validly assigned to which ports) and drops forged replies. This directly defeats the attack at the switch and is the primary technical control.
  • Static ARP entries for critical hosts, such as the gateway, so that a forged reply for that address is ignored, because the mapping is fixed and not learned. Effective but administratively heavy, so reserved for a few important mappings.
  • ARP monitoring tools that watch for the signs of poisoning: an IP address suddenly mapping to a new MAC address, or one MAC address claiming many IP addresses (the attacker's MAC appearing for both the victim and the gateway). These raise an alert on the poisoning itself.

Neutralising its value, and the durable control:

  • Encryption in transit. Because the attacker diverts but cannot decrypt, end-to-end encryption with certificate checking makes a successful man-in-the-middle nearly worthless: they relay ciphertext, and impersonation fails the certificate check. This is why the countermeasures chapter concludes that the deepest defence against the whole block is to encrypt, and to ensure clients verify certificates and do not click through warnings.

The professional recommendation combines them: Dynamic ARP Inspection to stop the poisoning, monitoring to detect attempts, and encryption everywhere so that even a successful attack yields only ciphertext. Defence in depth, because any one control may be absent on some segment.

A worked example, run as a defender

An assessor evaluates a client's exposure to a local man-in-the-middle, on the client's own network with authorisation, reasoning from configuration rather than by intercepting colleagues' traffic.

  • The access switches do not have Dynamic ARP Inspection enabled, so forged ARP replies would be accepted and a man-in-the-middle position could be established. Finding: the network does not prevent ARP poisoning at the switch.
  • However, the organisation uses HTTPS and a VPN throughout, so an attacker in the middle would relay only encrypted traffic and any impersonation would fail the certificate check. The exposure is therefore diversion of ciphertext, not disclosure of contents.
  • One internal application uses an unencrypted protocol. This is the serious finding, because for that application a man-in-the-middle would read and could alter the traffic.
  • No ARP monitoring is in place, so an attempt would not be detected. Finding: no detection of poisoning.

Recommendations, in order: enable Dynamic ARP Inspection (stop the poisoning); move the unencrypted application to an encrypted protocol (remove the one exposure that matters); add ARP monitoring (detect attempts); and set static ARP entries for the gateway on critical hosts. The assessor notes the general lesson: encryption already limits the damage to almost nothing except where a protocol is unencrypted, which is exactly where to focus.

munotes.in304

ARP Poisoning and the Man in the Middle

What beginners get wrong

  • Thinking ARP poisoning is a flaw in an implementation. It exploits a design decision: ARP has no authentication and hosts believe any reply, including unsolicited ones.
  • Believing being in the middle means being able to read the traffic. It means diverting the traffic; encrypted traffic is relayed as ciphertext and impersonation fails the certificate check.
  • Assuming the switch protects against it. ARP poisoning operates at the ARP level, and the switch delivers frames to the attacker's port correctly; Dynamic ARP Inspection is the switch feature that does stop it.
  • Overlooking integrity. A man-in-the-middle can alter unencrypted traffic, not only read it, so it threatens integrity as well as confidentiality.
  • Relying on a single control. Dynamic ARP Inspection, monitoring and encryption are combined, because any one may be missing on some segment.
  • Clicking through certificate warnings. The certificate check is what defeats impersonation by a man-in-the-middle; ignoring the warning discards that protection.

Quick revision

  • ARP maps an IP address to a MAC address on the local network, by broadcast request and reply, cached in the ARP cache. Every local conversation begins with it.
  • The enabling flaw: ARP has no authentication, so a host believes any reply, including unsolicited ones, and a later reply overwrites an earlier one.
  • ARP poisoning: the attacker sends forged replies telling the victim the gateway is at the attacker's MAC, and the gateway the victim is at the attacker's MAC, so both send their traffic to the attacker, who forwards it: the man-in-the-middle position, which sees and can alter traffic.
  • It defeats the switch, which delivers to the attacker's port correctly.
  • Crucial limit: it diverts but does not decrypt. Encrypted traffic is relayed as ciphertext and impersonation fails the certificate check; unencrypted traffic is fully exposed and alterable.
  • Countermeasures: Dynamic ARP Inspection (drops forged replies), static ARP entries for critical hosts, ARP monitoring, and, decisively, encryption in transit with certificate checking.

Test yourself

  1. What is ARP for, and which of its design properties makes poisoning possible?

ARP maps a known IP address to the MAC address needed for local delivery, by broadcasting a request and caching the reply. Poisoning is possible because ARP has no authentication: a host believes any ARP reply it receives, including unsolicited ones, without verifying that the responder truly owns the claimed IP address, and a later reply overwrites an earlier one.

munotes.in305

ARP Poisoning and the Man in the Middle

  1. Describe how ARP poisoning establishes a man-in-the-middle position.

The attacker sends forged ARP replies telling the victim that the gateway's IP address is at the attacker's MAC address, and telling the gateway that the victim's IP address is at the attacker's MAC address. Both update their ARP caches with these false mappings, so each sends toward the attacker traffic intended for the other, and the attacker forwards each packet on after reading it, sitting invisibly between the two parties.

  1. Why does ARP poisoning defeat a switch when MAC flooding might not?

Because it operates at the ARP level rather than by overwhelming the switch's forwarding table. The switch delivers frames correctly to the attacker's port, since the poisoned caches cause the victim and gateway to address their traffic to the attacker's MAC, which the switch legitimately maps to the attacker's port, so no switch failure is required.

  1. What is the crucial limit of the man-in-the-middle position, and what follows for defence?

That it diverts traffic but does not decrypt it: encrypted traffic is relayed as ciphertext the attacker cannot read or usefully alter, and any attempt to impersonate the far end fails the certificate check, whereas unencrypted traffic is fully exposed and alterable. It follows that end-to-end encryption with certificate verification makes a successful poisoning nearly worthless, so the unencrypted protocols are where the real exposure lies.

  1. Name the switch feature that directly stops ARP poisoning and explain how it works.

Dynamic ARP Inspection, a managed-switch feature that checks each ARP reply against a trusted database of legitimate IP-to-MAC bindings, derived from the switch's knowledge of which addresses are validly assigned to which ports, and drops any reply that does not match. Forged replies are therefore discarded before they can poison a host's cache.

Contents This chapter on its own page

munotes.in306

Chapter Sixty-Four

DNS Spoofing

Syllabus topic Module 1, "Network Sniffing and Man-in-the-Middle Attacks: ... DNS spoofing, and countermeasures"

In one line

DNS spoofing supplies a false answer to a name lookup, so that when a victim asks for the address of a site, they receive the attacker's address and connect to the attacker's server believing it is the real one. It rests on the DNS having no authentication, and it is defeated by DNSSEC, encrypted DNS, and, decisively, the certificate check.

In examination wording: DNS spoofing is the provision of a forged DNS response, causing a resolver or client to accept an incorrect name-to-address mapping and thereby to connect to a host chosen by the attacker; it exploits the absence of authentication in the base DNS protocol, and may be performed by a local attacker responding to queries or by corrupting a resolver's cache.

Where this fits

The DNS block of Module 1 taught how names resolve and named, in the resolution chapter, the design property this attack exploits: the base DNS protocol has no authentication, so a client accepts the first plausible answer that arrives, matching only the expected source, port and a transaction identifier. This chapter is that flaw turned into a redirection, and it belongs in the sniffing block because it is the third way, alongside MAC flooding and ARP poisoning, to place an attacker where the victim's traffic goes.

The difference in what each redirects is worth stating:

  • MAC flooding makes the switch broadcast, so the attacker sees traffic.
  • ARP poisoning redirects the victim's traffic through the attacker at the local-network level.
  • DNS spoofing sends the victim to the wrong server by giving a false address for a name, so the victim connects to the attacker directly, believing it is the real site.

How it works

Recall the resolution process: a client asks a resolver for the address of a name, and accepts the answer. DNS spoofing supplies a false answer, and there are two settings in which it is done.

As part of a local man-in-the-middle. Having already established a position (for example by ARP poisoning), the attacker sees the victim's DNS queries and answers them with forged responses before the real answer arrives, giving the attacker's own address for whatever names they choose. Because the base protocol accepts the first plausible reply, a forged reply that arrives first and matches the query's identifiers is believed. The victim then connects to the attacker's server for those names.

By corrupting a resolver's cache (cache poisoning). Instead of targeting one victim, the attacker gets a resolver to accept and cache a false mapping, which is then served to every user of that resolver until the cached entry's time to live expires. This is more powerful because it affects many victims from one success, and the time-to-live consequence from the resolution chapter applies: the false answer persists for the cached duration. The classic technique exploited weaknesses in how resolvers matched replies to queries, which is why modern resolvers randomise the query's source port as well as its transaction identifier, greatly increasing the work an attacker must do to have a forged reply accepted.

munotes.in307

DNS Spoofing

In both settings the result is the same: the victim believes a name maps to the attacker's address and connects there.

What the attacker gains, and the same crucial limit

Once the victim connects to the attacker's server believing it is the real one, the attacker can present a fake version of the site, to capture credentials, serve malicious content, or relay to the real site while reading the traffic.

But the same limit as ARP poisoning applies, and it is the reason the block converges on one conclusion:

  • Sending the victim to the wrong server does not give the attacker the real server's certificate. When the victim's browser connects to what it thinks is the bank, it checks the certificate presented against the name it asked for, and the attacker cannot present a valid certificate for the real name, because they do not hold the real site's private key and no trusted authority will issue them one for a name they do not control. So the browser raises a certificate warning, and a user who heeds it is protected.
  • For unencrypted connections, or where a user clicks through the warning, the redirection succeeds fully.

So DNS spoofing, like ARP poisoning, is defeated in practice by encryption with certificate checking: the redirection works, but the impersonation fails at the certificate. The attacker can send you to their server; they cannot make their server prove it is the bank.

The countermeasures

Three layers, the first two from the DNS-hardening chapter and the third the block's universal control.

DNSSEC signs DNS records cryptographically, so that a resolver which validates can detect a forged answer: a spoofed record lacks a valid signature from the zone's owner and is rejected. It addresses the authentication gap at its root, for the integrity of DNS answers, and is the direct defence against cache poisoning. Its limits, from the hardening chapter, are that it must be deployed by the zone owner and validated by the resolver, neither of which is universal, and that it protects integrity, not confidentiality.

Encrypted DNS (DNS over TLS or over HTTPS) protects the query and answer in transit, so a local attacker cannot see the query or inject a forged reply on the path, which defeats the local man-in-the-middle form of the attack. It complements DNSSEC: DNSSEC authenticates the data, encrypted DNS protects the channel.

munotes.in308

DNS Spoofing

Transport encryption with certificate checking, the block's decisive control. Even if a victim is given a false address, the connection to the attacker's server fails the certificate check for the real name, so the impersonation is caught. This is why the countermeasures chapter concludes that encrypting end to end and heeding certificate warnings is the defence that survives any redirection.

Supporting measures: resolvers that randomise source ports and transaction identifiers (raising the difficulty of the local injection), and, for the local-network form, the ARP-poisoning countermeasures of the previous chapter, since a local DNS spoof usually requires a man-in-the-middle position that Dynamic ARP Inspection would prevent.

A worked example, run as a defender

An assessor evaluates a client's exposure to DNS-based redirection, reasoning from configuration.

  • Internal services use TLS with the organisation's own certificate authority, so a victim redirected to a fake internal server would receive a certificate that fails the check for the real name, and the browser would warn. The exposure to impersonation is therefore small for these services.
  • The organisation's resolvers do not use DNSSEC validation and do not use encrypted DNS. Finding: cache poisoning and local injection are not prevented at the DNS layer, though the certificate check limits the impact.
  • One internal tool is accessed over plain HTTP. Serious finding: a successful DNS spoof to this tool would fully succeed, since there is no certificate to fail.
  • Users have historically been trained to click through certificate warnings for a legacy self-signed service. Finding, and an important one: this habit discards the very control that defeats impersonation, so it must be corrected and the legacy service given a proper certificate.

Recommendations: enable DNSSEC validation on the resolvers and consider encrypted DNS (close the DNS-layer gap); move the plain-HTTP tool to HTTPS (remove the one service with no certificate defence); fix the legacy service's certificate and retrain users never to click through warnings (restore the decisive control); and ensure the ARP-poisoning countermeasures are in place, since a local DNS spoof usually needs that position. The last recommendation is the one users least expect: the habit of dismissing certificate warnings is itself a serious weakness, because it defeats the control the whole block relies on.

What beginners get wrong

  • Thinking DNS spoofing lets the attacker impersonate any site fully. It sends the victim to the attacker's server, but the attacker cannot present a valid certificate for the real name, so an encrypted site's browser raises a warning.
  • Confusing the two forms. Local injection targets one victim on the path; cache poisoning corrupts a resolver and affects all its users until the time to live expires.
  • Believing DNSSEC encrypts DNS. It authenticates records (integrity) and does not provide confidentiality; encrypted DNS is the separate control for the channel.
  • Overlooking the certificate warning as the key defence. It is what defeats impersonation; training users to click through it discards the protection.
  • Forgetting the time-to-live consequence. A poisoned cache entry is served for its full duration, so the harm of a cache poisoning is multiplied by the number of the resolver's users and the length of the time to live.
  • Treating the local form as independent of ARP. A local DNS spoof usually requires a man-in-the-middle position, so the ARP-poisoning countermeasures also apply.
munotes.in309

DNS Spoofing

Quick revision

  • DNS spoofing gives a false name-to-address answer, so the victim connects to the attacker's server believing it is the real one. It exploits the DNS's lack of authentication (a client accepts the first plausible reply).
  • Two forms: local injection (answer a victim's query on the path, one victim) and cache poisoning (corrupt a resolver, all its users, for the entry's time to live). Modern resolvers randomise source port and transaction identifier to resist injection.
  • Same crucial limit as ARP poisoning: redirection succeeds, but the attacker cannot present a valid certificate for the real name, so an encrypted site's certificate check fails and the browser warns; unencrypted connections, or clicked-through warnings, are fully exposed.
  • Countermeasures: DNSSEC (signs records, defeats cache poisoning, integrity not confidentiality), encrypted DNS (protects the channel, defeats local injection), and decisively transport encryption with certificate checking; plus resolver randomisation and the ARP-poisoning controls for the local form.

Test yourself

  1. What does DNS spoofing achieve, and which protocol property does it exploit?

It causes a victim to receive a false name-to-address mapping, so that connecting to a name sends them to an address the attacker chose, typically the attacker's own server presenting a fake version of the intended site. It exploits the absence of authentication in the base DNS protocol, under which a client accepts the first plausible reply matching the expected source, port and transaction identifier, without verifying its authenticity.

  1. Distinguish the local-injection and cache-poisoning forms of the attack.

In local injection the attacker, usually already in a man-in-the-middle position, answers a specific victim's DNS queries with forged replies that arrive before the real answer, affecting that one victim. In cache poisoning the attacker gets a resolver to accept and cache a false mapping, which is then served to every user of that resolver until the entry's time to live expires, affecting many victims from one success.

  1. Why does DNS spoofing fail against an encrypted site even when the redirection succeeds?

Because sending the victim to the attacker's server does not give the attacker a valid certificate for the real site's name; when the victim's browser connects, it checks the presented certificate against the name it asked for, and the attacker cannot present one that a trusted authority has issued for a name they do not control, so the browser raises a certificate warning and a user who heeds it is protected.

munotes.in310

DNS Spoofing

  1. What do DNSSEC and encrypted DNS each defend against, and why are both needed?

DNSSEC cryptographically signs DNS records so a validating resolver can reject forged answers, defending the integrity of the data and particularly against cache poisoning; it does not provide confidentiality. Encrypted DNS protects the query and answer in transit, so a local attacker cannot read or inject on the path, defending against the local-injection form. They are complementary: one authenticates the data, the other protects the channel.

  1. Why is training users to click through certificate warnings described as a serious weakness in this context?

Because the certificate check is the control that defeats impersonation after a successful redirection, whether by DNS spoofing or ARP poisoning: it is what catches the attacker's server failing to prove it is the real site. Habitually dismissing the warning discards that protection, so a user conditioned to click through will connect to the attacker's fake server despite the browser having correctly detected the impersonation.

Contents This chapter on its own page

munotes.in311

Chapter Sixty-Five

Countermeasures: Switch Controls and Encryption in Transit

Syllabus topic Module 1, "Network Sniffing and Man-in-the-Middle Attacks: ... countermeasures to secure network communication"

In one line

MAC flooding, ARP poisoning and DNS spoofing all try to get a victim's traffic in front of the attacker. Encryption in transit accepts that they might succeed and makes success nearly worthless, so the deepest countermeasure to the whole block is to encrypt end to end and check certificates, backed by switch controls that stop or detect the diversion.

In examination wording: the network sniffing and man-in-the-middle attacks share the objective of positioning the attacker to observe or relay a victim's traffic; the corresponding countermeasures combine link-layer controls that prevent or detect the diversion (port security, Dynamic ARP Inspection, secure DNS) with end-to-end encryption and certificate validation that render intercepted traffic unreadable and impersonation detectable.

The one pattern behind three attacks

Look back over the block and every attack in it has the same goal, achieved three ways:

AttackHow it gets the traffic in front of the attacker
MAC floodingMakes the switch broadcast, so all traffic reaches every port
ARP poisoningRedirects the victim's traffic through the attacker at the local-network level
DNS spoofingSends the victim to the attacker's server by a false name lookup

Three mechanisms, one objective: put the attacker where the victim's traffic goes. Recognising this is what lets a defender reason about the countermeasures as a set rather than three unrelated lists, and it is the examinable synthesis of the block.

Because the objective is shared, the countermeasures fall into two kinds: those that stop or detect the diversion (specific to each attack), and the one that neutralises the diversion's value (common to all). A mature defence uses both, but the second is the deeper, and understanding why is the point of the chapter.

The decisive countermeasure: encryption in transit

The three attacks all get traffic to the attacker. The question that decides how much that matters is: what does the attacker have once they have the traffic?

If the traffic is unencrypted, they have everything: the contents, the credentials, the ability to alter it. If the traffic is encrypted end to end with certificate checking, they have almost nothing useful:

  • They see only ciphertext for the contents, so confidentiality holds.
  • They cannot alter the contents undetectably, because authenticated encryption detects tampering, so integrity holds.
  • If they try to impersonate the far end (as DNS spoofing and a relaying man-in-the-middle attempt), they cannot present a valid certificate for the real name, so the victim's client raises a warning, and a user who heeds it is protected.

So encryption does not try to stop the attacker getting the traffic, which the block showed is hard to guarantee across every segment and every protocol. It accepts that the traffic may reach the attacker and ensures that reaching it gains them nothing. That is a more robust posture than trying to prevent every possible diversion, because it does not depend on every switch being correctly configured or every ARP reply being inspected; it depends only on the traffic being encrypted, which the endpoints control.

munotes.in312

Countermeasures: Switch Controls and Encryption in Transit

This is why the same phrase has recurred through the block: being in the middle is not the same as being able to read the middle. The whole block converges on it.

The requirement encryption places on the user

Encryption's protection against impersonation runs through the certificate check, and that check can be discarded by the user, which is the one way the decisive control fails.

When a victim is redirected to an attacker's server, the browser's certificate check is what catches it: the attacker's certificate does not match the real name, so a warning appears. If the user clicks through the warning, they connect to the attacker's server anyway, and the protection is lost. So the human requirement is explicit and must be trained: never click through a certificate warning, and never deploy services that condition users to expect them (self-signed certificates on internal services are the usual cause, and they should be replaced with properly issued ones).

This is why the DNS chapter called the click-through habit a serious weakness: it is the single behaviour that defeats the block's strongest defence.

The supporting countermeasures, per attack

Encryption neutralises the value of a diversion; these stop or detect the diversion itself, and defence in depth uses them because encryption may be absent on some legacy protocol and a defender wants the attack stopped as well as neutralised.

Against MAC flooding: port security. Limit the MAC addresses learned per port and shut a port that exceeds it, so the switch's table cannot be flooded and it never fails open. Plus static MAC bindings, disabling unused ports, and storm control.

Against ARP poisoning: Dynamic ARP Inspection. Drop forged ARP replies by checking them against a trusted binding database. Plus static ARP entries for critical hosts such as the gateway, and ARP monitoring to alert on the signs of poisoning.

Against DNS spoofing: secure DNS. DNSSEC to reject forged records by signature, and encrypted DNS to stop a local attacker reading or injecting on the path, plus resolver randomisation of source ports and transaction identifiers.

Across all: monitoring and segmentation. Network monitoring detects the anomalies these attacks produce (a flood of new MAC addresses, an IP address suddenly on a new MAC, one MAC claiming many IPs), and segmentation limits how much traffic any single position can reach, so a foothold on one segment does not expose the whole network.

munotes.in313

Countermeasures: Switch Controls and Encryption in Transit

The countermeasure hierarchy

The block's conclusion, as a ranked list a student can reproduce:

  1. Encrypt everything in transit, end to end, with certificate checking, and never click through certificate warnings. This makes any successful diversion nearly worthless and is the control that does not depend on every network device being correctly configured.
  2. Enable the switch and DNS controls (port security, Dynamic ARP Inspection, secure DNS) to stop and detect the diversions themselves, as defence in depth.
  3. Monitor for the anomalies the attacks produce, so attempts are seen.
  4. Segment the network, so any single position reaches less.
  5. Eliminate unencrypted protocols, because they are the one case where a diversion still fully succeeds, and they are therefore where the residual risk concentrates.

The ordering reflects the block's argument: the durable protection is at the endpoints (encryption), and the network controls, while valuable, are the layer that can be misconfigured on any given switch, which is exactly why the endpoints must not depend on them.

A worked example, run as a defender

An assessor produces the network-communication section of a report for a client, synthesising the whole block.

  • Encryption in transit is used for most services (HTTPS, a VPN, SSH), so a successful sniff or man-in-the-middle would yield only ciphertext, and impersonation would fail the certificate check. The dominant positive finding, and the reason most of the block's attacks would gain little.
  • Two internal protocols are unencrypted. The concentrated residual risk: for these, any of the three diversions would fully succeed. Highest-priority recommendation: encrypt them.
  • Port security is enabled; Dynamic ARP Inspection is not; DNSSEC validation is not. Recommendations to enable the missing switch and DNS controls as defence in depth, noting that encryption already limits the impact of the ARP and DNS gaps to the unencrypted protocols.
  • Users were trained to accept certificate warnings for a legacy self-signed service. A serious finding, because it defeats the decisive control; fix the service's certificate and retrain.
  • Monitoring for ARP anomalies and MAC floods is absent. Recommendation to add it, so attempts are detected.

The report leads with the synthesis: because the organisation encrypts most traffic, the network-diversion attacks would mostly yield ciphertext, so the priorities are the unencrypted protocols and the certificate-warning habit, with the switch and DNS controls as defence in depth. That ordering is the block's thesis applied to a real estate.

What beginners get wrong

  • Trying to prevent every diversion and stopping there. Guaranteeing that no attacker ever gets traffic in front of them, across every switch and protocol, is hard; encryption makes the diversion not matter, which is more robust.
  • Thinking the switch and DNS controls are the main defence. They stop and detect the diversions, but they can be misconfigured on any device; the endpoint control, encryption, does not depend on the network being correct.
  • Overlooking the certificate warning. It is how impersonation is caught; clicking through it defeats the strongest defence, so it must never be trained or tolerated.
  • Leaving unencrypted protocols in place. They are the one case where a diversion fully succeeds, so they are the residual risk to eliminate.
  • Treating the three attacks as unrelated. They share one objective, get traffic in front of the attacker, which is why one control (encryption) addresses all three at once.
  • Forgetting monitoring and segmentation. Detection sees the attempts, and segmentation limits how much any position reaches.
munotes.in314

Countermeasures: Switch Controls and Encryption in Transit

Quick revision

  • The three attacks share one objective: put the attacker where the victim's traffic goes (MAC flooding by broadcast, ARP poisoning by redirection, DNS spoofing by a false address).
  • The decisive countermeasure is encryption in transit end to end with certificate checking: the attacker gets only ciphertext, cannot alter it undetectably, and cannot impersonate the far end without a valid certificate. It makes any successful diversion nearly worthless and does not depend on every network device being correct.
  • Its one human requirement: never click through a certificate warning, and replace services that condition users to expect them.
  • Supporting controls: port security (MAC flooding), Dynamic ARP Inspection and static ARP entries (ARP poisoning), DNSSEC and encrypted DNS (DNS spoofing), plus monitoring and segmentation.
  • Hierarchy: encrypt everything (endpoints), then switch and DNS controls (defence in depth), then monitoring, then segmentation, and eliminate unencrypted protocols as the concentrated residual risk.

Test yourself

  1. What single objective do MAC flooding, ARP poisoning and DNS spoofing share, and why does recognising it matter?

They all seek to position the attacker where the victim's traffic goes, MAC flooding by forcing the switch to broadcast, ARP poisoning by redirecting traffic through the attacker locally, and DNS spoofing by sending the victim to the attacker's server. Recognising it matters because it shows that one countermeasure, encryption in transit, addresses all three at once by making the diverted traffic worthless, so the defences can be reasoned about as a set.

  1. Why is encryption in transit described as a more robust posture than preventing every diversion?

Because guaranteeing that no attacker can ever get traffic in front of them requires every switch to be correctly configured and every ARP reply inspected across the whole network, which cannot be assured on every segment and protocol. Encryption instead accepts that the traffic may reach the attacker and ensures that reaching it gains them nothing, depending only on the endpoints encrypting, which they control.

  1. What are the three things encryption with certificate checking denies an attacker who has diverted the traffic?
munotes.in315

Countermeasures: Switch Controls and Encryption in Transit

The contents, because they see only ciphertext, so confidentiality holds; the ability to alter the contents undetectably, because authenticated encryption detects tampering, so integrity holds; and the ability to impersonate the far end, because they cannot present a valid certificate for the real name, so the victim's client raises a warning.

  1. What human behaviour can defeat the decisive countermeasure, and what should be done about it?

Clicking through a certificate warning, which discards the check that catches an attacker's server failing to prove it is the real site, so a redirected user connects to the attacker anyway. It should be addressed by training users never to click through such warnings and by replacing services, typically internal self-signed ones, that condition users to expect and dismiss them.

  1. Give the countermeasure hierarchy for this block and explain why encryption ranks first.

Encrypt everything in transit end to end with certificate checking; enable the switch and DNS controls (port security, Dynamic ARP Inspection, secure DNS) as defence in depth; monitor for the anomalies the attacks produce; segment the network; and eliminate unencrypted protocols. Encryption ranks first because it neutralises the value of any successful diversion and does not depend on every network device being correctly configured, whereas the switch and DNS controls, though valuable, can be misconfigured on any given device.

Contents This chapter on its own page

munotes.in316

Module II

Denial of service and botnets, session and web-server security, the OWASP Top Ten, SQL injection, buffer overflows, wireless security, malware analysis, exploit frameworks, and penetration testing methodology and reporting

munotes.in

Chapter Sixty-Six

Denial of Service: Attacking Availability

Syllabus topic Module 2, "Denial of Service and Botnet Architecture: Examine types of DoS/DDoS attacks ... Understand ... mitigation strategies"

In one line

A denial-of-service attack does not steal or alter anything; it makes a service unavailable by exhausting a resource. A distributed denial of service does it from many machines at once, which is why it cannot be stopped simply by blocking a source.

In examination wording: a denial-of-service attack aims to render a system or service unavailable to its legitimate users by exhausting a finite resource such as bandwidth, connection state, or processing capacity; a distributed denial-of-service attack employs many coordinated sources simultaneously, complicating attribution and defence.

Why availability is a category of its own

Every other attack in this book is, ultimately, about getting at data: reading it, altering it, or gaining the access that leads to it. A denial of service is different in a way that shapes everything about defending against it.

The attacker gains no data and often no access. Their entire goal is to stop the service working. So the motive is different, extortion (pay or we keep you down), competitive harm, protest, revenge, or distraction while another attack runs elsewhere, and, decisively, the defences are different, because there is no flaw to patch.

That last point is the one to hold from this chapter. You cannot "fix" being sent more traffic than your connection can carry, any more than you can fix a road being blocked by too many cars. So the response is not patching but capacity, filtering, and absorption: having enough resource, distinguishing attack traffic from legitimate traffic, and pushing the problem to somewhere with more capacity than the attacker can overwhelm. The whole mitigation block follows from this, and it is why denial of service has its own chapters rather than being a footnote to the others.

The three kinds, by what they exhaust

A resource is anything finite that the service needs, and each kind of attack exhausts a different one. Knowing the three, and that they need different mitigations, is the examinable core.

Volumetric. Flood the target with so much traffic that its network connection fills up, and legitimate traffic cannot get through. Measured in volume, and the "more water than the pipe can carry" attack. The following chapter covers it and the amplification that makes it possible.

Protocol. Abuse a weakness in how a protocol works to exhaust a specific resource with relatively little traffic. The SYN flood, which exhausts a server's table of half-open connections, is the classic, and it gets its own chapter because it follows directly from the handshake of Module 1. Measured in packets or connections rather than raw volume.

Application-layer. Send requests that are cheap for the attacker to send but expensive for the server to process, exhausting the application rather than the network. Low volume, and hard to distinguish from legitimate users, which is what makes it difficult to defend.

munotes.in317

Denial of Service: Attacking Availability

KindResource exhaustedMeasured inDistinctive difficulty
VolumetricNetwork bandwidthVolumeSheer scale; the pipe fills before the server sees it
ProtocolA specific finite structure (e.g. connection table)Packets/connectionsLittle traffic needed
Application-layerServer processingRequestsLooks like real users

Distributed, and why one source is not the model

A single machine attacking a large service usually cannot generate enough to overwhelm it, and even if it could, blocking one source address would stop it. So serious attacks are distributed: launched from many machines at once, which are typically a botnet of compromised computers and devices, the subject of a later chapter in this block.

Distribution changes the defensive problem fundamentally:

  • Blocking sources does not work. There are too many, they change, and they are often innocent owners' devices, so a block list is futile and can harm real users.
  • The traffic can be enormous, because it is the sum of many sources, far exceeding what any single site's connection can carry.
  • Attribution is hard, because the real attacker is behind the botnet's control, not among the sources.

This is why the practical defence for a large attack is upstream: a provider or specialised service with far more capacity than any single site absorbs and filters the attack before it reaches the target, which the mitigation chapter develops.

The legal and ethical position

A genuine denial-of-service attack disrupts a service and denies access to authorised users, which are acts under section 43(e) and (f) of the IT Act, and done to cause harm they invite section 66. This is not testable material only; it governs the profession directly:

  • Denial-of-service testing is almost universally forbidden in an engagement's rules of engagement, because a real disruption harms real users even when the intent is only to measure resilience. The rules-of-engagement chapter listed it among the standard prohibitions.
  • Where resilience must be assessed, it is done through design review and controlled tests arranged with the provider, not by actually flooding a production service.

So this block, like the rest of the book, is about understanding these attacks to recognise, survive and mitigate them, and the chapter describes no means of generating one.

A worked example, framed defensively

A small online shop is knocked offline by a flood that fills its internet connection. Reason through the defensive analysis:

  • The attack is volumetric: more traffic than the shop's connection can carry, so nothing on the shop's own server can help, because the connection is full before the server processes anything. This is the "cannot be patched" property in concrete form.
  • Blocking source addresses is futile: the traffic comes from thousands of compromised devices, too many to block, and many belonging to innocent owners.
  • The practical response is upstream: the shop's provider or a scrubbing service, which has far more capacity, filters the attack and forwards the legitimate traffic, restoring service. Arranged in advance, this works; arranged during the attack, it is too late.
  • The wider lesson for the shop: keep its own devices patched and off default passwords, so they never become part of someone else's botnet attacking a third party, which is a responsibility to others as well as to itself.
munotes.in318

Denial of Service: Attacking Availability

Nothing in the example generates traffic against anyone; it is analysis and response, which is the register of the whole block.

What beginners get wrong

  • Thinking a denial of service steals data. It attacks availability only and takes nothing; its harm is downtime, not disclosure.
  • Believing it can be patched. There is no flaw to fix in being sent too much traffic; the defences are capacity, filtering and absorption.
  • Trying to block source addresses in a distributed attack. There are too many, they change, and they are often innocent devices, so blocking is futile and can harm legitimate users.
  • Confusing the three kinds. Volumetric fills the pipe with volume; protocol exhausts a specific structure with little traffic; application-layer exhausts processing with cheap-to-send but expensive-to-serve requests. They need different mitigations.
  • Arranging mitigation during an attack. Upstream scrubbing and capacity must be in place beforehand; during an outage is too late.
  • Ignoring your own devices' role. An unpatched device on a default password can be conscripted to attack others; basic hygiene is a shared responsibility.

Quick revision

  • A denial of service attacks availability by exhausting a finite resource; it steals nothing and cannot be patched, so defences are capacity, filtering and absorption.
  • Three kinds by resource: volumetric (bandwidth, by volume), protocol (a specific structure such as the connection table, with little traffic), application-layer (server processing, by cheap-to-send expensive-to-serve requests that look like real users).
  • Distributed (DDoS): many sources, usually a botnet, so blocking sources is futile, the traffic can be enormous, and attribution is hard; the defence for large attacks is upstream.
  • Legally, a real attack is acts under s.43(e) and (f); denial-of-service testing is forbidden by nearly every engagement, and resilience is assessed by design review and provider-arranged tests, not by flooding production.

Test yourself

  1. Which property of the CIA triad does a denial-of-service attack target, and why does that make its defence unlike the rest of the book?

Availability. It makes the service unusable by exhausting a finite resource rather than exploiting a flaw, so there is nothing to patch; the defences are therefore capacity, filtering and absorption, distinguishing attack traffic from legitimate traffic and pushing the problem to somewhere with more capacity than the attacker can overwhelm, rather than fixing a vulnerability.

munotes.in319

Denial of Service: Attacking Availability

  1. Name the three kinds of denial-of-service attack by the resource each exhausts.

Volumetric, which exhausts network bandwidth by sheer volume; protocol, which exhausts a specific finite structure such as a server's connection table with relatively little traffic; and application-layer, which exhausts the server's processing capacity with requests that are cheap for the attacker to send but expensive for the server to handle and resemble legitimate use.

  1. Why does distribution make a denial-of-service attack much harder to defend against?

Because the attack comes from many sources at once, typically a botnet, so blocking source addresses is futile since there are too many, they change, and they are often innocent owners' devices; the combined traffic can far exceed any single site's capacity; and the real attacker is hidden behind the botnet's control, making attribution difficult.

  1. Why must denial-of-service mitigation be arranged before an attack rather than during one?

Because the practical defence for a large attack is upstream absorption and filtering by a provider or scrubbing service with greater capacity, and establishing that relationship and configuration takes time. During an active outage the service is already unreachable and there is no opportunity to set up the defence, so a response plan and standing arrangements must exist in advance.

  1. Why is denial-of-service testing almost always forbidden in an engagement, and how is resilience assessed instead?

Because a genuine test disrupts the service and denies access to legitimate users, which are acts under section 43(e) and (f) of the IT Act and cause real harm even when the intent is only to measure resilience. Resilience is instead assessed through design review of the mitigations in place and controlled tests arranged with the provider, not by actually flooding a production service.

Contents This chapter on its own page

munotes.in320

Chapter Sixty-Seven

Volumetric Attacks and Amplification

Syllabus topic Module 2, "Denial of Service and Botnet Architecture: Examine types of DoS/DDoS attacks including ... Smurf attacks"

In one line

A volumetric attack fills the target's connection with sheer traffic. Amplification is what lets a small attacker generate it: send a small request with the victim's address forged as the sender, to a service that answers with a much larger reply, so the reply floods the victim. It rests on source-address spoofing, which anti-spoofing filtering removes.

In examination wording: volumetric denial-of-service attacks saturate the target's network capacity; amplification (or reflection) attacks achieve high volume from limited attacker bandwidth by sending small requests, with the victim's address spoofed as the source, to third-party services that return much larger responses to the victim; the technique depends on the ability to forge source addresses.

Volumetric attacks

The simplest denial of service is the crudest: send more traffic than the target's internet connection can carry, so that legitimate traffic cannot get through. The target's own systems are irrelevant, because the connection is saturated before any packet reaches the server to be processed.

This is the "more water than the pipe can carry" attack, and it has one requirement: the attacker must be able to generate more traffic than the victim can receive. A single machine on an ordinary connection cannot do this against a well-connected service, which is why volumetric attacks are distributed (many sources) and often amplified (each source's traffic magnified). Amplification is the more interesting idea and the one MU's example illustrates.

The Smurf attack: the teaching case for amplification

The Smurf attack is largely historical, but it is the clearest illustration of amplification, which is why MU names it and why it is worth understanding precisely even though the specific attack no longer works.

Its mechanism combined two features:

  • A broadcast address: sending to it delivers to every machine on that network, so one packet becomes many.
  • Source-address spoofing: the sender's address in a packet can be forged, and the reply goes to the forged address, not the real sender.

The attack sent a small ICMP echo request (a ping) to a network's broadcast address, with the source address forged to be the victim's. Every machine on that network received the ping and dutifully replied, and because the source was forged, all of those replies went to the victim. One small packet from the attacker became many packets at the victim: the attack was amplified by the number of machines on the intermediate network, and the attacker's own bandwidth was tiny compared with the flood the victim received.

Smurf itself is dead, because networks no longer forward broadcast pings from outside (a configuration change made specifically to stop it). But the principle it demonstrates is very much alive, and it is the point of the chapter.

munotes.in321

Volumetric Attacks and Amplification

Amplification in general

The general pattern, of which Smurf is one instance:

  1. Find a service that answers a small request with a large reply, and that runs over a protocol where the source address is not verified (so the reply can be sent to a forged address). Connectionless protocols like UDP fit, because there is no handshake to prove the requester's address.
  2. Send many such small requests, each with the victim's address forged as the source.
  3. The services send their large replies to the victim, who is flooded by traffic they never requested, from services that are not the attacker.

The measure of an amplifier is its amplification factor: the ratio of reply size to request size. A service that answers a tiny request with a reply dozens or hundreds of times larger multiplies the attacker's bandwidth by that factor, so a modest attacker generates a huge attack.

The services abused this way are ordinary infrastructure misconfigured to answer strangers: certain DNS resolvers (a small query, a large response, which is why the DNS-hardening chapter said an open resolver harms third parties), NTP servers with the monitoring command enabled (the enumeration chapter's finding, a short request yielding a long client list), and various others such as SSDP on consumer devices. In every case the abused service is not the attacker's and not the victim's; it is an innocent third party whose misconfiguration lets it be used as a reflector and amplifier.

This is a category of harm the earlier chapters kept flagging: a service exposed to strangers can be turned against someone else. The organisation running an open resolver or an NTP server with monitoring enabled suffers no direct harm, which is exactly why they leave it open, and it becomes a weapon against a third party.

The root cause and the control that removes it

Amplification, and spoofed floods generally, depend on source-address spoofing: the attacker must be able to send packets claiming to come from the victim. Remove that ability and the whole technique collapses, because the replies would go back to the attacker, not the victim.

The control is anti-spoofing filtering, also called ingress and egress filtering (the practice referenced in the NTP chapter):

  • Egress filtering by a network operator drops outbound packets whose source address does not belong to that network. If every network did this, no attacker could send a packet forging a victim's address, because their own network would drop it at the door.
  • Ingress filtering drops inbound packets that claim to come from inside the network but arrive from outside.

Anti-spoofing is the single control that would starve amplification attacks at their source, and it is a long-standing recommendation. Its weakness is that it must be deployed by the operators of the networks the spoofed traffic leaves, who are not themselves the victims, so there is a collective-action problem: the network that could stop it is not the one that suffers. This is the same shape as the open-reflector problem, and it is why these attacks persist despite a known fix: the fix depends on parties other than the victim acting.

munotes.in322

Volumetric Attacks and Amplification

The complementary controls, for the operators of potential amplifiers, are the enumeration and DNS chapters' recommendations: do not run an open resolver, disable the NTP monitoring command, restrict services to the sources that need them, and rate-limit responses, so that even if spoofing occurs your service is not the amplifier.

Mitigating volumetric attacks as a victim

Since a victim cannot fix other people's spoofing or reflectors, their defences are about capacity and absorption, developed fully in the mitigation chapter:

  • Upstream scrubbing: a provider with vast capacity absorbs and filters the flood before it reaches the victim's connection. For a large volumetric attack this is the only practical defence, because the victim's own connection is the thing being overwhelmed.
  • Capacity and distribution: enough bandwidth, and services spread across many locations (anycast) so the attack is divided among them.
  • Filtering the obvious: a scrubbing service can drop traffic that is clearly part of an amplification attack, for example large DNS or NTP responses to a host that never sent the queries.

A worked example, framed defensively

An assessor reviews an organisation's exposure both as a potential victim and as a potential unwitting amplifier.

  • As a victim: the organisation has no upstream scrubbing arrangement, so a large volumetric attack would saturate its connection with no recourse. Finding: no volumetric mitigation; arrange upstream scrubbing in advance.
  • As an amplifier: the organisation runs a DNS resolver open to the internet and an NTP server with the monitoring command enabled. Findings: both can be used to amplify attacks against third parties. These are harms to others, which the organisation has no direct incentive to fix, which is precisely why an assessment must flag them.
  • The organisation's own network does not perform egress filtering, so a compromised device inside it could send spoofed traffic. Finding: enable anti-spoofing egress filtering, which prevents the organisation's network being used to launch spoofed attacks.

Recommendations: arrange upstream scrubbing (victim defence); close the open resolver and disable NTP monitoring (stop being an amplifier); and enable egress filtering (stop being a launch point). The report makes explicit that two of the three findings protect other people, a category organisations habitually neglect and an assessment should not.

munotes.in323

Volumetric Attacks and Amplification

What beginners get wrong

  • Thinking a volumetric attack exploits the server. It saturates the connection; the server is never reached. Nothing on the server can help.
  • Believing Smurf still works. The specific attack is dead (broadcast pings are no longer forwarded), but the amplification principle it teaches is alive in DNS, NTP and other reflectors.
  • Missing that the amplifier is a third party. The abused service is neither the attacker's nor the victim's; it is an innocent, misconfigured party used as a reflector.
  • Overlooking that you might be the amplifier. An open resolver or an NTP server with monitoring enabled harms others, which is why it is left open and why it must be flagged.
  • Forgetting the root cause. Amplification depends on source-address spoofing; anti-spoofing (ingress/egress) filtering would starve it, but must be deployed by the networks the spoofed traffic leaves.
  • Expecting the victim to fix spoofing. They cannot; their defences are capacity and upstream scrubbing.

Quick revision

  • Volumetric attacks fill the target's connection with sheer traffic; the server is never reached, so its own defences are irrelevant. They require generating more traffic than the victim can receive, hence distributed and often amplified.
  • Smurf is the teaching case (now dead): a small ping to a broadcast address with the victim's source spoofed, so every host replies to the victim. Amplification.
  • General amplification: small requests with the victim's forged source to a service that answers with a large reply, over an unverified protocol (often UDP); the amplification factor is reply-to-request size. Reflectors: open DNS resolvers, NTP with monitoring, SSDP, others, all innocent third parties.
  • Root cause: source-address spoofing; the control is anti-spoofing (ingress/egress) filtering, deployed by the networks the spoofed traffic leaves (a collective-action problem). Amplifier operators should also close open resolvers, disable NTP monitoring, restrict sources and rate-limit.
  • Victim defences: upstream scrubbing, capacity and anycast.

Test yourself

  1. How does a volumetric attack work, and why can the victim's own server do nothing about it?

It sends more traffic than the target's internet connection can carry, so the connection is saturated and legitimate traffic cannot get through. The victim's server can do nothing because the connection fills before any packet reaches the server to be processed, so no server-side configuration or capacity helps; the bottleneck is the pipe, not the machine.

  1. Explain the Smurf attack and what general principle it illustrates.

Smurf sent a small ICMP echo request to a network's broadcast address with the source address forged to be the victim's, so every machine on that network replied to the victim, turning one small packet into many at the victim. It illustrates amplification: using a forged source address and a service that answers a small request with a larger or multiplied response to make a small attacker generate a large flood.

munotes.in324

Volumetric Attacks and Amplification

  1. What properties must a service have to be usable as an amplifier?

It must answer a small request with a much larger reply, giving a high amplification factor, and it must run over a protocol where the source address is not verified, typically a connectionless protocol like UDP, so that the reply can be directed to a forged victim address rather than back to the real requester. Open DNS resolvers and NTP servers with monitoring enabled are common examples.

  1. What is the root cause of amplification attacks, and why does the fix persist unapplied?

The root cause is source-address spoofing, the ability to send packets forging the victim's address as the source. The fix is anti-spoofing ingress and egress filtering, which drops packets with forged source addresses, but it must be deployed by the operators of the networks the spoofed traffic leaves, who are not the victims and have little direct incentive, so a collective-action problem keeps it from being universal.

  1. Why should an assessment flag an organisation's open resolver even though it causes the organisation no direct harm?

Because an open resolver can be used as an amplifier and reflector in denial-of-service attacks against third parties, so it is a harm to others rather than to the organisation itself. Organisations habitually neglect such issues precisely because they suffer no direct consequence, which is exactly why an assessment must identify them, alongside recommending anti-spoofing filtering so the organisation's network cannot be used to launch spoofed attacks.

Contents This chapter on its own page

munotes.in325

Chapter Sixty-Eight

Protocol Attacks: the SYN Flood in Depth

Syllabus topic Module 2, "Denial of Service and Botnet Architecture: Examine types of DoS/DDoS attacks including SYN flooding"

In one line

A SYN flood exhausts a server's table of half-open connections by starting many handshakes and never completing them, so the table fills and no legitimate client can connect. It abuses the cost of the handshake, and SYN cookies remove that cost by not allocating the state at all until a connection is proven real.

In examination wording: a SYN flood is a protocol denial-of-service attack that sends numerous TCP connection requests without completing the three-way handshake, filling the target's finite backlog of half-open connections and preventing legitimate connections; it is mitigated principally by SYN cookies, which encode the connection state in the response rather than storing it, allocating resources only on receipt of a valid final acknowledgement.

Building on the handshake

The three-way handshake chapter of Module 1 established the cost that this attack weaponises, so recall it precisely.

To open a connection, the client sends SYN, the server replies SYN/ACK, and the client replies ACK. Between the second and third steps, the server is in the half-open (SYN-RECEIVED) state: it has sent SYN/ACK and is waiting for the final ACK. In that state the server has allocated resources, an entry in a finite structure often called the backlog, recording the pending connection's details, and it holds that entry until the ACK arrives or a timeout expires, often retransmitting the SYN/ACK a few times first.

That entry, held while waiting, is the resource the SYN flood exhausts. The handshake chapter flagged this exact consequence: the server must remember every half-open connection, and remembering is finite.

The mechanism

A SYN flood sends many SYN packets and never sends the final ACK. For each SYN, the server allocates a backlog entry and sends SYN/ACK, and then waits, because it has no way to know the client will never complete. The attacker sends the next SYN, and the next, and the backlog fills with entries for connections that will never be established.

Once the backlog is full, the server can accept no new connection requests, including from legitimate clients, whose SYN packets are dropped because there is no room to record them. The service is now unavailable, not because its connection is saturated (that would be volumetric) but because a specific, finite structure has been exhausted with very little traffic.

Two features make it a protocol attack rather than a volumetric one:

  • Little bandwidth is needed. A SYN packet is small, and it takes only enough of them to fill the backlog, which is far less traffic than a volumetric attack requires. The attack is efficient.
  • The source is usually spoofed. The attacker forges the source addresses of the SYN packets, both to hide and to ensure the SYN/ACK goes to an address that will not reply, so no ACK ever comes and the entry stays until timeout. This uses the same spoofing the amplification chapter relied on, and it means the same anti-spoofing filtering helps.
munotes.in326

Protocol Attacks: the SYN Flood in Depth

The retransmission behaviour worsens it: the server, expecting an ACK, retransmits each SYN/ACK several times before giving up, holding the entry for the full timeout, which is often many seconds. So each attacking SYN ties up an entry for a long time, and a modest rate of SYNs keeps the backlog permanently full.

The mitigation: SYN cookies

The elegant defence, and the reason it is worth teaching, is that it removes the resource the attack exhausts, so there is nothing left to fill.

The insight is that the server allocates state at SYN-RECEIVED before it knows the connection is real, which is exactly what the attacker abuses. SYN cookies invert this: the server allocates no state when it receives a SYN. Instead, it encodes the information it would have stored into the sequence number of the SYN/ACK it sends back, computed cryptographically from the connection's details. This encoded value is the "cookie".

Then:

  • If the client is legitimate, it sends the final ACK, which (by the protocol) carries the cookie value back. The server reconstructs the connection state from the cookie, verifies it, and establishes the connection, having stored nothing in the meantime.
  • If the SYN was part of a flood and no ACK ever comes, the server has spent no backlog entry, because it allocated none. There is nothing to fill.

So with SYN cookies, a flood of SYNs that are never completed costs the server almost nothing: it answers each with a computed SYN/ACK and forgets it, and only a genuine ACK causes any state to be created. The backlog can no longer be exhausted by half-open connections, because half-open connections no longer consume it.

SYN cookies have minor trade-offs (some rarely-used connection options cannot be carried in the cookie), so they are typically enabled to activate under attack, when the backlog is filling, rather than always. But they are a standard, widely available mitigation, and their existence is why the SYN flood, once devastating, is now a manageable and well-understood attack.

Other protocol attacks, briefly

The SYN flood is the archetype, and the same idea, exhausting a specific finite structure with little traffic, appears in other forms a student should recognise as the same category:

  • Attacks that open connections and then keep them half-open at the application level, holding a request incomplete so the server keeps a worker waiting (a slow-request attack, which shades into the application-layer chapter).
  • Attacks that exhaust other finite tables or state, such as connection-tracking tables in firewalls.
munotes.in327

Protocol Attacks: the SYN Flood in Depth

In each case the defence follows the SYN-cookie logic where possible: do not commit a scarce resource until the request is proven legitimate, and set timeouts and limits so that incomplete requests cannot accumulate.

A worked example, framed defensively

An assessor reviews a server's resilience to protocol denial of service, by inspecting configuration rather than by flooding it.

  • The server's operating system has SYN cookies available but not enabled to activate under attack. Finding: the backlog could be exhausted by a SYN flood. Recommendation: enable SYN cookies, which removes the resource the attack targets.
  • The network does not perform egress filtering, so spoofed SYNs could be sent from within, and inbound spoofed SYNs are not filtered. Finding: anti-spoofing would raise the difficulty of a SYN flood, since the flood relies on forged sources.
  • The backlog size is at the default; Finding, minor: increasing it raises the bar slightly, but is not a real fix on its own, because an attacker can send more SYNs; SYN cookies are the actual answer.
  • Upstream, the provider offers scrubbing that recognises SYN-flood patterns. Recorded as a positive control for large distributed floods that exceed what the host alone can absorb.

Recommendations, in order: enable SYN cookies (the definitive host mitigation); ensure anti-spoofing filtering; and rely on upstream scrubbing for distributed floods too large for the host. The assessor notes the pleasing point that the mitigation is not "more backlog" (an arms race the attacker wins) but "no backlog until the connection is real", which defeats the attack in principle rather than by degree.

What beginners get wrong

  • Confusing a SYN flood with a volumetric attack. A SYN flood exhausts a specific structure, the backlog, with little traffic; a volumetric attack fills the connection with sheer volume. Different resource, different mitigation.
  • Thinking a bigger backlog is the fix. It raises the bar slightly and the attacker simply sends more SYNs. SYN cookies remove the resource, which is the real fix.
  • Missing why the source is spoofed. Spoofing hides the attacker and ensures no ACK returns, so each entry is held for the full timeout; anti-spoofing filtering therefore helps.
  • Forgetting the retransmission cost. The server retransmits each unanswered SYN/ACK, holding the entry for many seconds, so a modest SYN rate keeps the backlog full.
  • Not connecting it to the handshake. The attack is a direct consequence of the handshake's cost of remembering half-open connections, which the handshake chapter named.
  • Believing SYN cookies have no trade-offs. They cannot carry some rarely-used options, so they are often enabled to activate under attack rather than always; still the standard mitigation.

Quick revision

  • The handshake leaves the server half-open (SYN-RECEIVED) after SYN/ACK, holding a backlog entry until the final ACK or a timeout; that entry is the resource.
  • A SYN flood sends many SYNs and never the final ACK, filling the backlog so legitimate clients cannot connect. A protocol attack: little bandwidth, usually spoofed sources so no ACK returns, worsened by SYN/ACK retransmission holding entries for the full timeout.
  • SYN cookies: allocate no state on SYN; encode the needed state into the SYN/ACK sequence number (the cookie); reconstruct it only when a valid ACK returns. A flood then costs almost nothing because half-open connections consume no backlog. Standard, often enabled to activate under attack.
  • The same "do not commit a scarce resource until the request is proven" logic answers other protocol attacks. Anti-spoofing filtering and upstream scrubbing support the defence.
munotes.in328

Protocol Attacks: the SYN Flood in Depth

Test yourself

  1. What resource does a SYN flood exhaust, and how does the attack exhaust it?

It exhausts the server's finite backlog of half-open connections. After the server replies to a SYN with SYN/ACK it holds a backlog entry awaiting the final ACK; a SYN flood sends many SYNs and never sends the ACK, so the server allocates an entry for each and holds it until timeout, filling the backlog so that legitimate clients' connection requests are dropped for lack of room.

  1. Why is a SYN flood classed as a protocol attack rather than a volumetric one?

Because it exhausts a specific finite structure, the connection backlog, using very little bandwidth, rather than saturating the target's network connection with sheer volume. Only enough small SYN packets to fill the backlog are needed, so the attack is efficient and its effect depends on the size of a data structure, not on out-flooding the pipe.

  1. How do SYN cookies mitigate the attack?

They cause the server to allocate no state when it receives a SYN, instead encoding the information it would have stored into the sequence number of the SYN/ACK it returns, computed cryptographically from the connection details. The state is reconstructed and the connection established only when a legitimate final ACK returns carrying that value, so a flood of SYNs that are never completed consumes no backlog entries and the backlog can no longer be exhausted.

  1. Why does the attacker usually spoof the source addresses of the SYN packets?

To hide their identity and, more importantly, to ensure that the server's SYN/ACK is sent to an address that will not respond, so no final ACK ever arrives and each backlog entry is held for the full timeout. Because the attack relies on forged sources, anti-spoofing ingress and egress filtering raises its difficulty.

  1. Why is increasing the backlog size not a real solution?

Because it only raises the threshold slightly, and the attacker can simply send more SYN packets to fill the larger backlog, making it an arms race the attacker wins. SYN cookies solve the problem in principle by removing the resource the attack targets, allocating no backlog state until a connection is proven legitimate, so there is nothing left to exhaust.

Contents This chapter on its own page

munotes.in329

Chapter Sixty-Nine

Application-Layer Denial of Service

Syllabus topic Module 2, "Denial of Service and Botnet Architecture: Examine types of DoS/DDoS attacks"

In one line

An application-layer attack sends requests that are cheap to send and expensive to serve, exhausting the server's processing rather than its bandwidth. It uses little traffic and looks like real users, so volume-based defences miss it, and the answer is to make expensive operations cost the attacker as much as they cost the server.

In examination wording: an application-layer denial-of-service attack targets the resources consumed by processing requests, such as processing time, memory, or backend queries, by issuing requests that are inexpensive for the attacker to generate but costly for the server to fulfil; because the traffic volume is low and resembles legitimate use, it evades defences based on traffic volume.

Why this one is different

The previous two attacks were about quantity: a volumetric attack sends too much traffic for the pipe, a SYN flood sends enough small packets to fill a table. Both are recognisable because the traffic is abnormal in volume or in shape.

An application-layer attack is about asymmetry of cost, and it is recognisable by neither volume nor shape, which is the whole difficulty. The attacker sends valid requests, in modest numbers, that happen to be expensive for the server to answer. Each request is cheap for the attacker (a small HTTP request) and expensive for the server (a complex database query, a large report, an operation that holds a worker for a long time). A relatively small number of such requests can exhaust the server's capacity to process anything, while the network connection is nowhere near full and the requests individually look entirely legitimate.

The defensive consequence is stark: the volume-based defences that work against the other kinds do not work here. There is no flood to detect, no abnormal packet, no saturated pipe. Blocking by rate alone risks blocking legitimate users, because the attack's rate may be within normal bounds. This is why application-layer attacks are the hardest of the three to defend against, and why the answer lies inside the application rather than in the network.

The forms it takes

Several patterns, all instances of the cost-asymmetry idea:

Expensive requests. Requests that trigger costly work: a search with no filters returning everything, a query that forces a full scan, a report that aggregates a large dataset, an operation that resizes or processes a large file. One such request may cost the server thousands of times what it costs the attacker to send.

Slow requests. Requests deliberately sent or received slowly, so that the server keeps a connection and a worker occupied for a long time waiting for the request to complete or the response to be read. A server has a finite number of workers, and holding each one idle-but-occupied with a slow request exhausts them with very little traffic and very few connections. This is the application-layer analogue of the SYN flood's half-open connections, at the request level, and it is a classic and effective technique.

munotes.in330

Application-Layer Denial of Service

Repeated expensive operations. Repeatedly triggering an operation the application performs that is costly and perhaps unbounded: a login that runs a slow password hash (ironically, the deliberately-slow hashing that protects passwords can be abused to exhaust the server if login attempts are unlimited), a resource-intensive API call, or an action that consumes memory.

Amplification within the application. A single request that causes the application to do disproportionate work internally, such as a query whose complexity the attacker controls, or an operation that expands input into much larger processing.

Why it is hard to distinguish from real users

The defining difficulty, stated plainly for the examination: an application-layer attack can be indistinguishable from legitimate heavy use at the level of individual requests. A real user might run an expensive report; the attacker runs many. A real client might be on a slow connection; the attacker feigns one. So a defender cannot simply block "bad" requests, because they are shaped like good ones, and blocking by volume risks legitimate users doing legitimate but heavy things.

Distinguishing therefore requires context rather than the request alone: is this one source making many expensive requests; is the pattern automated rather than human; is the request expensive out of proportion to any plausible need. This is harder than pattern-matching a flood, which is why the defences are more about designing the application to limit cost than about filtering traffic.

The defences: make the application cost-aware

Because the attack exploits the application doing expensive work cheaply for the attacker, the defences make that work bounded, rate-limited, and, where possible, as costly for the attacker as for the server.

  • Rate limiting per client and per operation, especially on expensive operations. A user does not need to run the heavy report fifty times a minute; limiting it protects the resource without affecting legitimate use. The limit is set per the operation's cost, so cheap operations are limited loosely and expensive ones tightly.
  • Bounding expensive operations. Cap the size of results, require filters on searches that would otherwise scan everything, paginate large datasets, limit the complexity a request may demand, and set timeouts so no single request can hold a worker indefinitely.
  • Timeouts and limits on slow requests. Require a request to arrive within a time limit and a response to be read within one, and cap how long a worker may be held, so slow-request attacks cannot accumulate held workers. This is the direct analogue of the SYN-cookie logic: do not let an incomplete request tie up a scarce resource.
  • Authentication and cost for expensive actions. Requiring authentication for the most expensive operations means an attacker must have accounts, which is a barrier; and where appropriate, a proof-of-work or a challenge (such as a CAPTCHA on repeated expensive anonymous operations) makes the request cost the attacker something, restoring the symmetry the attack destroyed.
  • Caching. Serving expensive-but-common results from a cache means repeated identical requests cost little, removing the asymmetry for cacheable operations.
  • Resource isolation. Ensuring that one expensive operation cannot consume all the server's capacity, for example by limiting the workers or memory a given operation type may use, so the rest of the application keeps working.
  • Monitoring for the pattern. Watching for one source making disproportionately expensive requests, or for a rise in slow or incomplete requests, which is the context-based detection the attack requires.
munotes.in331

Application-Layer Denial of Service

Upstream and application-firewall defences help less here than against volumetric attacks, precisely because the traffic looks legitimate, though modern application-protection services do apply behavioural analysis to spot the pattern. The durable defence is in the application's own design.

A worked example, framed defensively

An assessor reviews an application for application-layer denial-of-service resilience, by examining its behaviour and configuration.

  • The search feature accepts a query with no required filters and will return and process the entire dataset, taking seconds of server time per request. Finding: an expensive operation with no bound, exploitable by a small number of requests. Recommendation: require filters, paginate, cap result size, and set a timeout.
  • The server has no per-request timeout, so a slowly-sent request can hold a worker indefinitely. Finding: vulnerable to slow-request attacks. Recommendation: enforce request and response timeouts and cap worker hold time.
  • The login runs a deliberately-slow password hash and has no rate limit, so repeated login attempts can exhaust processing. Finding: the password-protecting slow hash can be turned into a denial-of-service lever without rate limiting. Recommendation: rate-limit login attempts per source and per account.
  • Expensive report generation is not rate-limited or cached. Recommendation: rate-limit and cache.

The report's theme is that these are design findings, not traffic findings: each is the application doing expensive work cheaply for a requester, and each fix makes the work bounded or costly to trigger. The assessor establishes them by examining the application's behaviour, not by attacking it, which is the register of the block.

What beginners get wrong

  • Expecting a flood. There is none; the attack uses modest traffic and valid requests, which is why volume-based defences miss it.
  • Trying to block by rate alone. The attack's rate may be within normal bounds, and blocking by rate risks legitimate heavy users; distinguishing needs context, and the durable defence is bounding cost in the application.
  • Overlooking slow-request attacks. Holding workers with slowly-sent requests exhausts a finite pool with very little traffic, the application-layer analogue of the SYN flood.
  • Ignoring self-inflicted cost asymmetries. An unlimited expensive operation, including the deliberately-slow password hash, becomes a lever; rate-limit expensive operations.
  • Relying on upstream scrubbing. It helps less here because the traffic looks legitimate; the defence is in the application's design.
  • Not requiring filters or bounds on expensive queries. An unbounded search or report is an invitation.
munotes.in332

Application-Layer Denial of Service

Quick revision

  • An application-layer attack exploits cost asymmetry: requests cheap to send, expensive to serve, exhausting processing not bandwidth. Little traffic, looks like real users, so volume-based defences miss it.
  • Forms: expensive requests (unfiltered searches, heavy reports), slow requests (holding workers occupied, the SYN-flood analogue at the request level), repeated expensive operations (including abusing a slow password hash without rate limiting), and in-application amplification.
  • Hard to distinguish from legitimate heavy use per request; distinguishing needs context (one source, disproportionate cost, automated pattern).
  • Defences make the application cost-aware: rate limit per client and per operation, bound expensive operations (filters, pagination, result caps, complexity limits, timeouts), timeouts on slow requests, authentication or challenges for expensive actions, caching, resource isolation, and monitoring for the pattern.

Test yourself

  1. What resource does an application-layer denial-of-service attack exhaust, and why do volume-based defences fail against it?

It exhausts the server's processing resources, such as processing time, memory, workers or backend queries, by sending valid requests that are cheap to generate but expensive to fulfil. Volume-based defences fail because the traffic is low in volume, normal in shape, and composed of legitimate-looking requests, so there is no flood, abnormal packet or saturated connection to detect.

  1. What is a slow-request attack, and to which earlier attack is it analogous?

It sends or receives requests deliberately slowly so that the server keeps a connection and a worker occupied for a long time awaiting completion, exhausting the finite pool of workers with very little traffic and few connections. It is analogous to the SYN flood, which exhausts the connection backlog with half-open connections; here the exhaustion is of workers held by incomplete requests at the application level.

  1. Why can a deliberately-slow password hash become a denial-of-service lever?

Because the slow hash that protects stored passwords costs the server meaningful processing per login attempt, so if login attempts are not rate-limited an attacker can trigger many of them cheaply and exhaust the server's processing. The protective cost of the hash, intended to slow attackers guessing offline, is turned against the server online unless login attempts are limited per source and per account.

  1. Why is distinguishing this attack from legitimate use difficult, and what is needed to do it?
munotes.in333

Application-Layer Denial of Service

Because individual malicious requests are valid and resemble legitimate heavy use, such as a genuine user running an expensive report, so no single request is identifiably bad and blocking by rate risks legitimate users. Distinguishing requires context rather than the request alone: whether one source is making many disproportionately expensive requests, whether the pattern is automated, and whether the cost is out of proportion to any plausible need.

  1. What is the general principle behind the defences, and give three concrete measures?

The principle is to make the application cost-aware, so that expensive work is bounded and, where possible, costs the attacker as much as the server, removing the asymmetry the attack exploits. Concrete measures include rate-limiting expensive operations per client, bounding those operations with required filters, pagination, result caps and timeouts, and enforcing timeouts on slow requests so incomplete requests cannot hold workers indefinitely.

Contents This chapter on its own page

munotes.in334

Chapter Seventy

Botnets: Architecture and Command and Control

Syllabus topic Module 2, "Denial of Service and Botnet Architecture: ... Understand botnet structures and mitigation strategies"

In one line

A botnet is a network of compromised computers and devices under one attacker's control, directed through command-and-control infrastructure. Its architecture decides how it is taken down, and its existence is why keeping your own devices patched protects other people, not only yourself.

In examination wording: a botnet is a collection of compromised hosts, called bots, that execute an attacker's instructions received through a command-and-control channel; botnets provide the many coordinated sources required for distributed denial-of-service and other large-scale attacks, and their command-and-control architecture, whether centralised or peer-to-peer, determines their resilience to disruption.

Why a botnet exists

The distributed attacks of this block need many sources: a distributed denial of service needs many machines to generate the traffic, and other criminal activities (spam, fraud, credential stuffing, currency mining) benefit from many machines and many addresses. No attacker owns thousands of machines, so they borrow them, by compromising other people's computers and devices and controlling them remotely, usually without the owners' knowledge.

The result is a botnet, and the machines in it are bots (or zombies). The scale can be very large, and increasingly the bots are not personal computers but internet-of-things devices, cameras, routers, recorders and other appliances, which are numerous, poorly secured, rarely updated, always on, and often reachable from the internet with default credentials. The enumeration and password chapters' warnings about default credentials and forgotten devices are, from the other side, exactly how devices are recruited.

The architecture

A student should know the parts and, more importantly, why the arrangement of the parts matters.

  • The bots: the compromised machines, running the attacker's software, awaiting instructions.
  • The command-and-control (C2) channel: how the attacker sends instructions to the bots and receives results. This is the heart of the botnet and its most important feature for defence.
  • The botmaster: the attacker who issues commands.

The command-and-control architecture comes in two broad forms, and the difference decides how the botnet is disrupted:

Centralised. The bots contact one or a few control servers to receive instructions. Simple to operate and responsive, but it has a single point of failure: if the control servers are identified and taken down or blocked, the botmaster loses contact with the bots and the botnet is disabled. Attackers mitigate this with techniques to make the control point harder to pin down (frequently changing addresses, using intermediaries), but the structural weakness remains, and centralised botnets are disrupted by attacking the control channel.

Peer-to-peer. The bots relay instructions among themselves, with no single control server; the botmaster injects a command into the network and it propagates. Much harder to take down, because there is no single point to attack, and disrupting it requires either dismantling many nodes or subverting the peer protocol. Resilient, at the cost of being more complex to build and slower to command.

munotes.in335

Botnets: Architecture and Command and Control

The examinable point: the architecture is a trade-off between the attacker's convenience and the botnet's resilience, and it dictates the takedown strategy. Centralised botnets are attacked at the control channel; peer-to-peer botnets require attacking the network itself.

How a botnet is disrupted

Because the control channel is the key, botnet takedowns, usually conducted by security firms, researchers and law enforcement acting together, target it:

  • Seizing or sinkholing the control servers of a centralised botnet, so the bots can no longer receive commands. Sinkholing redirects the bots' attempts to contact their controller to a monitored server, which both disables the botnet and reveals its size.
  • Disrupting the naming or addressing the bots use to find their controller, for example taking over the domains they are programmed to contact.
  • For peer-to-peer botnets, subverting the peer protocol or coordinating the removal of many nodes, which is harder.

None of this is the individual defender's job, but understanding it explains why the architecture matters and why the control channel is where the pressure is applied.

Why this concerns everyone: your device as a bot

The most important defensive point in the chapter, and the one that connects it to the whole book: an ordinary person's insecure device is what botnets are built from.

A router or camera left on its default password, an unpatched home computer, a device with an exposed service, any of these can be compromised and conscripted into a botnet, and then used to attack someone else. The owner may notice nothing, because the device still works; it is merely also, in the background, part of an attack on a third party.

This has two consequences the book has been building toward:

  • Basic device hygiene is a responsibility to others, not only self-protection. Patching your devices, changing default credentials, and not exposing services needlessly keeps your devices from becoming weapons against third parties. The default-credential and forgotten-device findings of the enumeration chapters are, from this angle, contributions to everyone's safety.
  • The internet-of-things problem is collective. The devices most easily recruited are consumer appliances their owners do not think of as computers and never update, and there are enormous numbers of them. This is why large botnets today are often built from such devices, and why the security of the whole depends partly on the security of the least-maintained parts.

So the chapter closes the loop opened in the denial-of-service framing chapter: keeping your own devices secure is part of defending against attacks that are not aimed at you, because it denies the attacker the sources they need.

munotes.in336

Botnets: Architecture and Command and Control

A worked example, framed defensively

An assessor reviews an organisation's exposure to being part of botnet activity, which is a category organisations rarely consider.

  • Several internet-of-things devices on the network (cameras, a building-management controller) run on default credentials and unpatched firmware, reachable from internal networks and, for one, from the internet. Finding: these devices are prime botnet-recruitment targets, and if compromised would attack third parties from the organisation's network.
  • The network does not perform egress filtering, so a compromised device could send spoofed attack traffic outward. Finding: no anti-spoofing, connecting to the amplification chapter.
  • There is no monitoring for the outbound traffic patterns a bot produces (regular connections to unfamiliar external addresses, participation in floods). Finding: bot activity would go unnoticed.

Recommendations: change default credentials and patch or isolate the internet-of-things devices (deny recruitment); enable egress filtering (prevent spoofed attacks leaving); segment the devices onto their own network so a compromise is contained; and monitor outbound traffic for the command-and-control and attack patterns a bot exhibits. The report frames these as protecting others as well as the organisation, which is the botnet chapter's distinctive contribution: an organisation can be a victim of a denial of service, and it can also, unknowingly, be part of one.

What beginners get wrong

  • Thinking a botnet is exotic. It is ordinary compromised computers and, increasingly, consumer devices, borrowed at scale because no attacker owns enough machines.
  • Ignoring the architecture's significance. Centralised botnets are disrupted at the control channel (a single point of failure); peer-to-peer botnets are resilient and harder to take down. The structure dictates the takedown.
  • Assuming only your own security is at stake. An insecure device becomes a weapon against third parties, so device hygiene is a responsibility to others.
  • Overlooking internet-of-things devices. They are numerous, poorly secured, rarely updated and always on, which is exactly why modern botnets are built from them.
  • Not monitoring outbound behaviour. A bot still lets its host work normally; its presence shows in outbound connections to controllers and in attack participation, not in the device failing.
  • Forgetting egress filtering. A compromised device on a network without it can send spoofed attacks outward.

Quick revision

  • A botnet is many compromised hosts (bots) controlled by a botmaster through a command-and-control (C2) channel; it supplies the many sources distributed attacks need. Increasingly built from poorly-secured internet-of-things devices.
  • Architecture: centralised (bots contact control servers; responsive but a single point of failure, disrupted by taking down the control channel) or peer-to-peer (bots relay among themselves; resilient, no single point, harder to take down). The structure dictates the takedown strategy.
  • Takedowns target the control channel: seizing or sinkholing control servers, disrupting the naming bots use, or attacking the peer network.
  • Your insecure device becomes a weapon against others: basic hygiene (patching, changing defaults, not exposing services) denies recruitment and is a responsibility to third parties. Segment IoT devices, enable egress filtering, and monitor outbound behaviour.
munotes.in337

Botnets: Architecture and Command and Control

Test yourself

  1. What is a botnet, and why do distributed attacks require one?

A botnet is a network of compromised computers and devices, called bots, that carry out an attacker's instructions received through a command-and-control channel. Distributed attacks require one because they need many coordinated sources, such as the many machines needed to generate a distributed denial-of-service flood, and no attacker owns enough machines, so they compromise and borrow other people's, usually without the owners' knowledge.

  1. Compare centralised and peer-to-peer command-and-control architectures.

In a centralised architecture the bots contact one or a few control servers, which is simple and responsive but creates a single point of failure, so identifying and taking down the control servers disables the botnet. In a peer-to-peer architecture the bots relay instructions among themselves with no central server, which is far more resilient because there is no single point to attack, at the cost of greater complexity and slower command propagation.

  1. How does the command-and-control architecture determine how a botnet is disrupted?

Because the control channel is the key: a centralised botnet is disrupted by attacking that channel, seizing or sinkholing the control servers or disrupting the naming the bots use to find them, which cuts the botmaster off from the bots. A peer-to-peer botnet has no such single point, so disrupting it requires subverting the peer protocol or coordinating the removal of many nodes, which is much harder.

  1. Why does keeping your own devices secure protect other people?

Because an insecure device, such as one left on a default password or unpatched, can be compromised and conscripted into a botnet and then used to attack third parties, while the owner notices nothing because the device still functions. Patching, changing default credentials and not exposing services needlessly denies the attacker the sources they need, so device hygiene is a contribution to everyone's safety, not only self-protection.

  1. Why are internet-of-things devices particularly attractive for building botnets?

Because they are numerous, frequently secured with default credentials, rarely if ever updated, always powered on, and often reachable from the internet, so they are easy to compromise and remain compromised. Their owners typically do not think of them as computers or maintain them, which is why large modern botnets are commonly assembled from such devices.

Contents This chapter on its own page

munotes.in338

Chapter Seventy-One

DDoS Mitigation: the Layered Defence

Syllabus topic Module 2, "Denial of Service and Botnet Architecture: ... Understand ... mitigation strategies"

In one line

No single control stops a serious distributed denial of service. The defence is layered: capacity and distribution to absorb, protocol and application controls to resist, upstream scrubbing to filter what is too large for the site, anti-spoofing to starve amplification, and a response plan arranged before the attack.

In examination wording: mitigation of distributed denial-of-service attacks combines provisioning of capacity and geographic distribution, protocol-level defences such as SYN cookies, application-level cost controls and rate limiting, upstream traffic scrubbing by a high-capacity provider, network anti-spoofing filtering, and prepared incident-response arrangements, because the different attack types are countered at different layers and none alone is sufficient.

Why layered, and matched to the attack

The block established three kinds of attack, each exhausting a different resource, and the single most important idea in mitigation follows directly: each kind is mitigated at a different layer, so the defence must cover all the layers.

Attack kindWhere it is mitigated
Volumetric (fills the pipe)Upstream, by capacity and scrubbing, because the pipe fills before the site sees it
Protocol (exhausts a structure)At the host and network, by SYN cookies and connection controls
Application-layer (exhausts processing)In the application, by cost controls and rate limiting

A defence that addresses only one layer fails against the others: a site with vast application-level protection is still knocked offline by a volumetric flood, and a site with huge bandwidth is still exhausted by an application-layer attack it processes willingly. So mitigation is necessarily a set of controls at different layers, which is the examinable structure of the chapter.

The layers of defence

Capacity and distribution. Having more resource than a moderate attack can overwhelm, and spreading it so an attack is divided. Anycast is the key technique: one address is served from many locations, so a distributed attack is split among them rather than concentrated on one, and each location handles a fraction. Content-delivery networks apply this at scale, absorbing large attacks by distributing them across a global infrastructure. Capacity alone is not a full defence, because a large enough attack exceeds any fixed capacity, but it raises the threshold and buys time.

Upstream scrubbing. The practical defence for a large volumetric attack, for the reason the framing chapter gave: the victim's own connection is the thing being saturated, so the filtering must happen upstream, before the traffic reaches that connection. A scrubbing service, with capacity far beyond any single site, receives the traffic, filters out the attack, and forwards the legitimate part. This is arranged in advance, because it requires directing the site's traffic through the scrubbing provider, which cannot be set up during an attack.

Protocol defences. SYN cookies for SYN floods (the protocol chapter), connection rate limits, and firewall connection-tracking tuned so its own tables cannot be exhausted. These operate at the host and network and address the protocol kind.

munotes.in339

DDoS Mitigation: the Layered Defence

Application defences. Rate limiting per client and per operation, bounding expensive operations, timeouts on slow requests, caching, and resource isolation (the application-layer chapter). These operate in the application and address the kind that looks like legitimate use.

Anti-spoofing filtering. Ingress and egress filtering (the amplification chapter) starves amplification and spoofed floods of the forged source addresses they depend on. It is deployed by network operators and is the control that would reduce these attacks across the whole internet if universal.

Rate limiting and traffic shaping. Limiting how much any single source may send, and prioritising traffic, which helps against sources that are individually identifiable, though less so against a large distributed attack where each source is modest.

Detection and traffic analysis. Recognising an attack early, distinguishing it from a legitimate traffic spike (a product launch, a news event), and identifying its kind so the right layer's controls are engaged. Misidentifying a legitimate spike as an attack, and blocking real users, is its own failure, so detection must be careful.

The response plan is itself a control

The chapter's distinctive point, and one students under-value: the most important preparation is a plan made before any attack.

A distributed denial of service is a time-critical event: the service is down, and every minute of downtime has a cost. There is no time during an attack to arrange a scrubbing service, work out who to call, or decide how to reroute traffic. So the plan must exist in advance and must cover:

  • Who to contact: the upstream provider, the scrubbing service, and the internal responders, with out-of-band contact details, because the usual channels may themselves be affected.
  • The standing arrangements: a scrubbing service on standby, agreements with the provider, and the technical means to redirect traffic through the scrubber quickly.
  • The decision authority: who decides to invoke the mitigations, so the response is not delayed by needing approval.
  • The runbook: the steps to take, tested, so the response is executed rather than improvised.
  • Communication: how to tell users the service is affected, on a channel that is not itself down.

An organisation that has arranged scrubbing, knows who to call, and has practised the response will recover in minutes; one that has not will spend the first, most damaging period of the attack setting up what should already have existed. This is why "have a response plan" is not advice but a control, and it is the note the block ends on.

munotes.in340

DDoS Mitigation: the Layered Defence

What a single site can actually do

A realistic point, because not every organisation can afford global infrastructure. A small site cannot out-capacity a large botnet, so its practical defences are:

  • Use a provider or service that includes DDoS protection, which many hosting and content-delivery services now do, effectively renting the capacity and scrubbing.
  • Enable the host and application controls it does control: SYN cookies, rate limiting, bounded operations, timeouts.
  • Have the response plan and the contacts ready.
  • Keep its own devices secure so it does not contribute to others' attacks (the botnet chapter).

The honest summary for a small site: the heavy lifting against a large volumetric attack must be bought (an upstream service with capacity), because it cannot be self-provided; what the site does itself is the protocol and application layers and the preparation.

A worked example, framed defensively

An assessor produces the denial-of-service section of a report, synthesising the block.

  • Volumetric: the site has no upstream scrubbing arrangement, so a large flood would saturate its connection with no recourse. Highest-priority recommendation: arrange DDoS protection through the provider or a scrubbing service in advance.
  • Protocol: SYN cookies are not enabled. Recommendation: enable them.
  • Application: the expensive search and report operations are unbounded and unthrottled. Recommendation: rate-limit and bound them.
  • Anti-spoofing: no egress filtering. Recommendation: enable it, both to resist and to avoid contributing to others' attacks.
  • Response plan: there is no plan, no scrubbing contact, and no tested runbook. A serious finding, because without it the first and most damaging period of any attack would be spent improvising. Recommendation: create and test a response plan with standing arrangements and out-of-band contacts.

The report's structure is the block's: each attack kind mapped to its layer, and the response plan flagged as the control most organisations lack. The assessor establishes all of it by reviewing configuration and preparation, not by attacking the service.

What beginners get wrong

  • Looking for a single anti-DDoS control. There is none; the three kinds are mitigated at different layers, so the defence must cover all of them.
  • Relying on capacity alone. A large enough attack exceeds any fixed capacity; capacity raises the threshold and buys time but is not a full defence.
  • Trying to filter a volumetric attack at the site. The connection is already saturated; filtering must be upstream, by a high-capacity provider.
  • Arranging scrubbing during an attack. It requires redirecting traffic and cannot be set up while the service is down; it must be a standing arrangement.
  • Neglecting the response plan. It is the control most under-prepared, and its absence wastes the most damaging early period of an attack on improvisation.
  • Mistaking a legitimate spike for an attack. Blocking real users during a product launch or news event is its own failure; detection must distinguish the two.
munotes.in341

DDoS Mitigation: the Layered Defence

Quick revision

  • Layered by attack kind: volumetric mitigated upstream (capacity, anycast, scrubbing), protocol at the host/network (SYN cookies, connection controls), application-layer in the application (rate limiting, bounded operations, timeouts). No single layer suffices.
  • Upstream scrubbing is the practical defence for large volumetric attacks, because the site's own connection is what is saturated; arranged in advance.
  • Anti-spoofing (ingress/egress) starves amplification; detection must distinguish an attack from a legitimate spike.
  • The response plan is a control: contacts (out-of-band), standing scrubbing arrangements, decision authority, a tested runbook, and user communication, all prepared before an attack.
  • A small site buys DDoS protection through a provider, enables the host and application controls it owns, prepares the plan, and keeps its own devices secure.

Test yourself

  1. Why must denial-of-service mitigation be layered rather than a single control?

Because the three kinds of attack exhaust different resources and are mitigated at different layers: volumetric attacks upstream by capacity and scrubbing, protocol attacks at the host and network by controls such as SYN cookies, and application-layer attacks within the application by cost controls and rate limiting. A defence at only one layer leaves the others open, so covering all the layers is necessary.

  1. Why must a large volumetric attack be mitigated upstream rather than at the target?

Because a volumetric attack saturates the target's own internet connection, so by the time the traffic reaches the site the connection is already full and no filtering at the site can help. The filtering must happen upstream, at a provider or scrubbing service with capacity far beyond the site's, which receives the traffic, removes the attack, and forwards only the legitimate part.

  1. What is anycast, and how does it help against distributed attacks?

Anycast serves a single address from many geographic locations, so traffic to that address is routed to the nearest location. Against a distributed attack it divides the attack among the many locations rather than concentrating it on one, so each location handles only a fraction, which is how content-delivery networks absorb large attacks by spreading them across a global infrastructure.

  1. Why is a response plan described as a control rather than merely good practice?

Because a distributed denial of service is a time-critical event in which the service is already down and every minute is costly, and there is no time during an attack to arrange scrubbing, determine who to call, or decide how to reroute traffic. A plan prepared in advance, with standing arrangements, out-of-band contacts, decision authority and a tested runbook, is what allows recovery in minutes rather than after a prolonged improvised response, so its existence materially reduces the harm.

  1. What can a small site that cannot self-provide large capacity realistically do?
munotes.in342

DDoS Mitigation: the Layered Defence

Use a hosting provider or content-delivery service that includes DDoS protection, effectively renting the capacity and scrubbing it cannot provide itself; enable the host and application controls it does own, such as SYN cookies, rate limiting, bounded operations and timeouts; prepare and test a response plan with ready contacts; and keep its own devices secure so it does not contribute to attacks on others.

Contents This chapter on its own page

munotes.in343

Chapter Seventy-Two

Sessions and Tokens: Why They Exist

Syllabus topic Module 2, "Session Hijacking and Token Security: Analyze session management vulnerabilities"

In one line

The web protocol has no memory, so after you log in a site remembers you with a session token, a secret string your browser sends with every request. For the life of the session, that token is as good as your password, which is why the rest of the block is about protecting it.

In examination wording: because HTTP is stateless, each request being independent, a web application maintains the identity of a logged-in user across requests by issuing a session identifier, or token, that the browser returns with subsequent requests; possession of a valid token is sufficient to be treated as the authenticated user, so the token is a credential requiring the same protection as a password.

Why a token is needed at all

HTTP, the protocol of the web, is stateless: each request is independent, and the server does not inherently know that this request comes from someone who logged in a moment ago. Without something extra, a user would have to send their password with every single request, which is both insecure (the password would be transmitted constantly) and impractical.

The solution is the session token. When you log in successfully, the server generates a token, a long random string, associates it with your logged-in session on the server, and sends it to your browser. The browser stores it and sends it back with every subsequent request, usually in a cookie. On each request the server looks up the token, finds the associated session, and knows this request is from you, already authenticated. So you log in once, and the token carries your authenticated identity through the rest of your visit.

This bridges the gap between a stateless protocol and the stateful experience of being logged in, and it is used by essentially every web application.

Why the token is as powerful as the password

Here is the fact the whole block rests on, so state it precisely.

Once issued, the token stands in for your identity. The server treats any request carrying a valid token as coming from the authenticated user, without re-checking the password, because the whole point of the token is to avoid re-checking. So anyone who possesses a valid token is treated as that user, for as long as the token is valid.

The consequence is stark: an attacker who obtains your session token does not need your password. They present the token, and the server treats them as you: your account, your data, your privileges. The token is therefore a credential, exactly as sensitive as the password, and for the duration of the session it is arguably more dangerous, because it is transmitted with every request and is often less carefully protected than the password was.

munotes.in344

Sessions and Tokens: Why They Exist

This is why the block exists and why every attack in it aims at the token: session hijacking is taking over a session by obtaining its token, and it bypasses the password entirely, along with any strength that password had. A sixteen-character password protects nothing if the token it produced can be stolen.

What a good token must be

Since the token is a credential, it must have the properties a credential needs, and these anticipate the attacks:

  • Unpredictable. It must be generated with enough randomness (entropy) that an attacker cannot guess or calculate a valid one. A token derived from a sequence, a timestamp, or a weak random source can be predicted, which is one of the attacks in the next chapter. This connects to the cryptographic-weaknesses chapter: a token is only as unguessable as the randomness that made it.
  • Long enough that brute-force guessing is infeasible, for the same reason a password must be long.
  • Secret in transit and at rest. It must not be exposed to anyone but the user and the server, which requires HTTPS in transit and care in how the browser stores it.
  • Bound to a single session and invalidated when that session ends.
  • Limited in lifetime, so a stolen token is useful only briefly.

Each of these is a defence against a specific attack, which is why the next chapters can be read as "here is how a token is stolen or guessed, and here is the property that prevents it".

Where the token lives

The token is usually stored in a cookie, a small piece of data the browser holds for a site and sends automatically with each request to that site. Cookies are convenient for this because the browser handles sending them, and they can carry security attributes (the subject of a later chapter) that control how they are protected.

Tokens can also be held in other browser storage and sent explicitly by the site's script, an arrangement common in modern applications. The trade-offs between the two are a detail the block returns to; for now the point is that the token is stored on the client and sent with requests, and wherever it is stored, protecting it is the goal.

A crucial distinction the block will use: the server keeps the session (the record of who you are and what you are doing), and the client keeps the token (the key that points to that session). The token is not itself the session; it is the key to it. Stealing the key gives access to the session, which is why protecting the key is everything.

munotes.in345

Sessions and Tokens: Why They Exist

A worked example

Asha logs in to her bank. Trace what happens:

  1. She sends her username and password once, over HTTPS.
  2. The server verifies them, creates a session recording that this session belongs to Asha and is authenticated, generates a long random token, and sends it to her browser in a cookie.
  3. Her browser sends that cookie with every subsequent request. Each time, the server looks up the token, finds Asha's session, and serves her account data without asking for the password again.
  4. When she logs out, the server invalidates the session, so the token no longer points to anything and is useless.

Now suppose an attacker obtains that token while it is valid. They send it with a request, the server looks it up, finds Asha's authenticated session, and serves them her account data, because the server cannot tell the request did not come from Asha: it carries her valid token. The attacker never knew her password, and her password's strength was irrelevant. That is session hijacking, and the block is about the ways the token can be obtained and the properties and controls that prevent each.

What beginners get wrong

  • Thinking hijacking needs the password. It needs the token, which is stolen or guessed without the password ever being involved, so it bypasses the password and its strength entirely.
  • Believing a strong password protects the session. It protects the login; once the token is issued, the token is what matters, and it can be stolen independently.
  • Confusing the token with the session. The server holds the session; the client holds the token, which is the key to it. Stealing the key gives access to the session.
  • Treating the token as less sensitive than the password. It is a credential of equal sensitivity, and it is transmitted with every request, so it is often more exposed.
  • Assuming a token is safe because it looks random. It is only unguessable if generated with sufficient entropy from a secure source; a predictable token is a guessable credential.

Quick revision

  • HTTP is stateless, so after login a site issues a session token (a long random string) that the browser returns with each request; the server looks it up to know the user is authenticated. Log in once, the token carries the identity.
  • The token stands in for the identity: any request with a valid token is treated as that user, without re-checking the password, so possessing the token is as good as knowing the password, for the session's life. This is why hijacking bypasses the password and its strength.
  • A good token is unpredictable (enough entropy, from a secure source), long, secret in transit and at rest, bound to one session, and limited in lifetime. Each property prevents a specific attack.
  • The token is usually held in a cookie (sent automatically, can carry security attributes) or other browser storage. The server holds the session; the client holds the token, the key to it.
munotes.in346

Sessions and Tokens: Why They Exist

Test yourself

  1. Why does a web application need a session token, and what problem does it solve?

Because HTTP is stateless, so each request is independent and the server does not inherently know that a request comes from someone who logged in earlier. Without a token, the user would have to send their password with every request, which is insecure and impractical. The token, issued at login and returned with each subsequent request, lets the user authenticate once and have their identity carried through the visit.

  1. Why is possessing a session token as good as knowing the password?

Because the server treats any request carrying a valid token as coming from the authenticated user, without re-checking the password, since avoiding that re-check is the token's purpose. So an attacker who obtains a valid token is treated as that user, with their account, data and privileges, without needing the password, and the password's strength is irrelevant once the token can be stolen.

  1. What is the distinction between the session and the token, and why does it matter?

The session is the server's record of who the user is and what they are doing; the token is the value held by the client that points to that session. The token is the key to the session, not the session itself. It matters because stealing the key gives access to the session, so protecting the token is what protects the session.

  1. What properties must a good session token have, and which attack does each prevent?

It must be unpredictable, generated with sufficient entropy from a secure source, which prevents guessing or calculating a valid token; long, which prevents brute forcing; secret in transit and at rest, which prevents theft by sniffing or from the browser; bound to a single session and invalidated when it ends; and limited in lifetime, which limits the usefulness of a stolen token.

  1. Why does a strong password not protect a user against session hijacking?

Because session hijacking targets the token, not the password: the token is obtained by theft or prediction after login, and the server then treats the attacker as the user on the strength of the token alone. The password secured the initial login, but once the token is issued it is the token that grants access, and it can be stolen independently of how strong the password was.

Contents This chapter on its own page

munotes.in347

Chapter Seventy-Three

How a Session Is Stolen: Prediction, Sniffing and Script

Syllabus topic Module 2, "Session Hijacking and Token Security: ... sequence prediction ... and prevention mechanisms"

In one line

A session token is obtained three ways: predicted if it is not truly random, sniffed off the wire if the connection is not encrypted, or stolen through the browser if a script can read it. Each route has one defence: strong random tokens, HTTPS, and the HttpOnly flag.

In examination wording: session tokens are compromised principally by prediction, exploiting insufficient randomness to guess a valid token; by interception, capturing a token transmitted over an unencrypted connection; and by theft through client-side script, typically via cross-site scripting, reading a token accessible to JavaScript; the corresponding preventions are high-entropy tokens, transport encryption, and cookie attributes preventing script access.

Three routes, three defences

The previous chapter established that the token is a credential as powerful as the password. This chapter is how an attacker gets it, and the organising idea is that there are essentially three routes, each closed by one specific measure:

RouteWhat it exploitsThe defence that closes it
PredictionA token that is not truly randomStrong, high-entropy tokens
SniffingA token sent over an unencrypted connectionHTTPS everywhere
Theft via scriptA token a script can readThe HttpOnly cookie flag

A student who learns the three routes and their three defences can analyse any session-theft finding, which is the examinable structure.

Prediction (sequence prediction)

If tokens are not generated with enough randomness, an attacker can guess or calculate a valid one without stealing anything, and this is MU's "sequence prediction".

The classic failure is a token that is sequential or derived from a predictable value. If session tokens are assigned in order, and an attacker sees that their own token is a particular number, they can try the numbers around it, one of which is another user's current session. If tokens are derived from the time of login, an attacker who knows roughly when a victim logged in can narrow the possibilities. If tokens are produced by a weak (non-cryptographic) random generator, their sequence can sometimes be reconstructed from a few observed values.

In every case the flaw is insufficient entropy: the token does not contain enough unpredictability, so the space of valid tokens is small enough to search or infer. This connects directly to the cryptographic-weaknesses chapter's point that keys, salts and tokens must come from a cryptographically secure random source: a token is only as unguessable as the randomness that produced it.

The defence: strong random tokens. Generate tokens with enough entropy, from a cryptographically secure source, that guessing is infeasible, exactly as a password's keyspace must be large. A token of sufficient length and true randomness cannot be predicted, calculated, or searched, which closes this route entirely. It is a property of how the token is generated, set once in the framework and correct thereafter.

munotes.in348

How a Session Is Stolen: Prediction, Sniffing and Script

Sniffing (interception in transit)

If the connection carrying the token is not encrypted, an attacker who can see the traffic reads the token off the wire and replays it, taking over the session.

The sniffing block of Module 1 supplies the mechanism: on a local network an attacker who has captured traffic (by defeating the switch, or on an open wireless network) sees everything sent unencrypted, and a session cookie sent over plain HTTP is right there in the request, in the clear. The attacker copies it, sends it with their own request, and is now the victim.

A subtle and important case: even if the login page uses HTTPS, if any subsequent request is sent over plain HTTP, the cookie is sent with it (unless protected, the next chapter's subject) and captured. So the whole session, not just the login, must be encrypted, which is why "HTTPS everywhere" rather than "HTTPS on the login page" is the requirement.

The defence: HTTPS everywhere, so the token is always inside the encryption and a sniffer sees only ciphertext. This is the transport-encryption conclusion of the sniffing block applied to the token: capturing the traffic gains nothing because the token is encrypted. Paired with the Secure cookie flag (next chapter), which ensures the browser never sends the cookie over an unencrypted connection even by accident, this route is closed.

Theft through the browser (cross-site scripting)

The third route does not touch the network at all. If an attacker can run script in the victim's browser in the site's context, that script can read the token and send it to the attacker.

This is the cross-site scripting flaw, which has its own chapters later; here the point is its consequence for sessions. If a site has an XSS vulnerability, an attacker's script running on the page can access the site's cookies and other storage, read the session token, and exfiltrate it. The victim need do nothing but view a page containing the injected script; the theft is silent.

This route is particularly dangerous because it bypasses the network defences: HTTPS does not help, because the script runs on the legitimate page after decryption, and strong tokens do not help, because the token is read, not guessed.

The defence: the HttpOnly cookie flag. A cookie marked HttpOnly cannot be read by JavaScript in the page; it is sent by the browser with requests but is invisible to script. So even if the site has an XSS flaw, the script cannot read an HttpOnly session cookie, and this route is closed for that cookie. (Fixing the XSS flaw itself is also necessary, and is the later chapters' subject, but HttpOnly protects the token specifically even where a flaw exists.) Note that a token held in other browser storage read by script is not protected this way, which is one argument for keeping session tokens in HttpOnly cookies.

munotes.in349

How a Session Is Stolen: Prediction, Sniffing and Script

Why the three-way split matters

The value of organising the attacks this way is that the defences are independent and all necessary:

  • HTTPS stops sniffing but does nothing against prediction or script theft.
  • Strong tokens stop prediction but do nothing against sniffing or script theft.
  • HttpOnly stops script theft but does nothing against sniffing or prediction.

So a site is only protected against session theft if it has all three, and a common mistake is to have one and believe the session is secure. A site with HTTPS but predictable tokens is vulnerable; a site with strong tokens but no HttpOnly is vulnerable to XSS-based theft. The next chapters add fixation and the cookie flags, completing the set.

A worked example, framed defensively

An assessor reviews a web application's session handling and maps each finding to a route.

  • Session tokens are a short incrementing number. Prediction route open: an attacker can try nearby numbers to hijack other sessions. Fix: strong high-entropy tokens.
  • The site uses HTTPS on the login page but serves some later pages over plain HTTP, and the session cookie lacks the Secure flag. Sniffing route open: the cookie is sent in the clear on those pages and can be captured. Fix: HTTPS everywhere and the Secure flag.
  • The session cookie is not marked HttpOnly, and the site has a reflected XSS flaw. Script-theft route open: injected script can read and exfiltrate the token. Fix: mark the cookie HttpOnly (and fix the XSS).
  • After these, the assessor confirms all three routes are closed: strong tokens, HTTPS everywhere with Secure, and HttpOnly.

The report presents the three routes and their defences as a set, noting that closing only one or two leaves the session stealable by the others, which is the chapter's central lesson.

What beginners get wrong

  • Thinking one defence secures the session. The three routes are independent; a site needs strong tokens and HTTPS everywhere and HttpOnly, because each defence closes only its own route.
  • Believing sequential or time-based tokens are acceptable. They are predictable; tokens must be high-entropy from a secure random source.
  • Encrypting only the login page. The token is sent with every request; any request over plain HTTP exposes it, so HTTPS everywhere is required.
  • Assuming HTTPS protects against script theft. The script runs on the decrypted page, so HTTPS does not help; HttpOnly is the defence.
  • Assuming HttpOnly protects a token in other browser storage. HttpOnly applies to cookies; a token in storage readable by script is not protected, which favours HttpOnly cookies for session tokens.
  • Forgetting that XSS-based theft is silent. The victim only views a page; no click or interaction is needed.
munotes.in350

How a Session Is Stolen: Prediction, Sniffing and Script

Quick revision

  • Three routes to a token, three defences: prediction (weak tokens) closed by strong high-entropy tokens; sniffing (unencrypted connection) closed by HTTPS everywhere (and the Secure flag); theft via script (XSS) closed by the HttpOnly flag.
  • Sequence prediction: sequential, time-based or weak-random tokens can be guessed or calculated; the flaw is insufficient entropy. A token is only as unguessable as its randomness source.
  • Sniffing: a cookie on any plain-HTTP request is captured, so encrypt the whole session, not just the login.
  • Script theft bypasses network defences (HTTPS and strong tokens do not help), because the script reads the token on the decrypted page; HttpOnly makes the cookie invisible to script.
  • The defences are independent and all necessary; one alone does not secure the session.

Test yourself

  1. What are the three routes by which a session token is obtained, and the single defence for each?

Prediction, exploiting insufficient randomness to guess or calculate a token, defended by strong high-entropy tokens; sniffing, capturing a token sent over an unencrypted connection, defended by HTTPS everywhere; and theft through client-side script, typically via cross-site scripting reading the token, defended by the HttpOnly cookie flag.

  1. What is sequence prediction, and what is the underlying flaw?

It is guessing or calculating a valid session token because tokens are predictable, for example sequential, derived from the time of login, or produced by a weak random generator whose sequence can be reconstructed. The underlying flaw is insufficient entropy: the token does not contain enough unpredictability, so the space of valid tokens is small enough to search or infer, and the fix is generating tokens with adequate entropy from a cryptographically secure source.

  1. Why must the whole session be encrypted rather than only the login page?

Because the session token is sent with every request, so if any request after login travels over plain HTTP the cookie is transmitted in the clear on that request and can be captured by a sniffer, allowing the session to be hijacked. Encrypting only the login protects the credentials at login but leaves the token exposed on later unencrypted requests, which is why HTTPS everywhere, with the Secure flag, is required.

  1. Why do HTTPS and strong tokens not defend against cross-site-scripting theft of a token, and what does?

Because the malicious script runs in the victim's browser on the legitimate page after the traffic has been decrypted, so HTTPS gives no protection, and the token is read directly rather than guessed, so its strength is irrelevant. The defence is the HttpOnly cookie flag, which makes the session cookie invisible to JavaScript, so injected script cannot read it even where an XSS flaw exists.

munotes.in351

How a Session Is Stolen: Prediction, Sniffing and Script

  1. Why must a site have all three defences rather than relying on one?

Because the three routes are independent and each defence closes only its own route: HTTPS stops sniffing but not prediction or script theft, strong tokens stop prediction but not sniffing or script theft, and HttpOnly stops script theft but not sniffing or prediction. A site with only one or two defences remains vulnerable to the routes the others would have closed.

Contents This chapter on its own page

munotes.in352

Chapter Seventy-Six

Cross-Site Request Forgery

Syllabus topic Module 2, "Session Hijacking and Token Security: ... prevention mechanisms"

In one line

Cross-site request forgery tricks a logged-in victim's browser into sending a request to a site where they are authenticated, so the request arrives carrying their session cookie and is treated as genuine. It exploits that the browser attaches the cookie automatically, and it is defeated by SameSite cookies and anti-forgery tokens.

In examination wording: cross-site request forgery is an attack in which a malicious site causes a victim's browser to send an unintended request to a different site where the victim is authenticated; because the browser automatically includes the session cookie, the request is processed as though the victim intended it, enabling state-changing actions without the attacker knowing the session token.

The mechanism

The attack rests on one behaviour of the browser: when a request is made to a site, the browser automatically attaches that site's cookies, including the session cookie, regardless of what caused the request. That automatic attachment is convenient, and it is the flaw CSRF exploits.

The sequence:

  1. The victim is logged in to a target site (say their bank), so their browser holds a valid session cookie for it.
  2. The victim visits, or is lured to, a malicious page (on the attacker's site, or a page the attacker can influence).
  3. That page causes the victim's browser to send a request to the target site, for a state-changing action, such as a funds transfer or a change of settings. The request can be triggered without the victim's awareness by ordinary web mechanisms.
  4. Because the request goes to the target site, the browser automatically attaches the victim's session cookie, so the request arrives authenticated.
  5. The target site, seeing a valid session cookie, processes the request as though the victim intended it.

The attacker has caused an action on the victim's account without knowing the session token and without the victim's intent. They did not steal anything; they made the victim's own browser send an authenticated request.

The crucial insight, and the examinable one: the attacker never sees the response. The browser sends the request with the cookie and receives the response, but the attacker's page, being on a different site, cannot read that response (the browser's same-origin protections prevent it). So CSRF is effective for state-changing actions (transfer money, change email, delete something), where causing the action is the goal, and not for reading data, because the attacker cannot see what comes back. This is why CSRF and XSS differ in what they achieve.

CSRF against XSS: the distinction students must master

These two are confused constantly, and the confusion is worth dispelling precisely, because it is a favourite examination point.

Cross-site scripting (XSS)Cross-site request forgery (CSRF)
What runs whereThe attacker's script runs on the target site in the victim's browserThe attacker's site makes the victim's browser send a request to the target site
What the attacker gainsFull control on the page: read the response, steal the token, act as the user, read dataCause a state-changing action; cannot read the response
Reads data?YesNo
Needs a flaw in the target?Yes, an XSS flawNo target flaw needed; exploits normal cookie behaviour
Defended byOutput encoding, Content-Security-Policy, HttpOnly (for the token)SameSite cookies, anti-forgery tokens
munotes.in362

Cross-Site Request Forgery

The one-line contrast to remember: XSS runs the attacker's code on your site; CSRF makes your browser send a request to your site. XSS is more powerful (it can do everything, including stealing the token and reading data), which is why a site with XSS is in deeper trouble; CSRF is narrower (state-changing actions only) but needs no flaw in the target, only that the target relies on the cookie alone to authenticate a request.

The defences

CSRF is defeated by making an authenticated request require something the attacker's site cannot supply, beyond the automatically-attached cookie.

Anti-forgery tokens (CSRF tokens). The primary defence. The target site includes, in each form or state-changing request, a secret token that is unique to the user's session and unpredictable, and it checks that the token is present and correct before acting. The attacker's site, being on a different origin, cannot read this token (same-origin protections again), so it cannot include it in the forged request, which is therefore rejected. The token is not the session cookie; it is an additional secret that must accompany state-changing requests, and it defeats CSRF because the attacker cannot know it.

SameSite cookies. The attribute from the previous chapter. If the session cookie is set to a restrictive SameSite, the browser does not attach it to cross-site requests, so the forged request arrives without the session cookie and is not authenticated. This closes the attack at the browser level, and modern browsers defaulting to a restrictive SameSite has substantially reduced CSRF's prevalence. It is a strong defence, and combined with anti-forgery tokens it provides defence in depth.

Additional measures:

  • Requiring re-authentication or confirmation for the most sensitive actions (re-enter the password to change email or transfer above a threshold), so an automatic request alone cannot perform them.
  • Checking the request's origin where reliable, to confirm it came from the site's own pages.
  • Not performing state-changing actions on simple requests that are easy to forge, using methods and request shapes that browsers restrict for cross-site use.

The combination to recommend: SameSite cookies plus anti-forgery tokens on all state-changing requests, with re-authentication for the most sensitive, which closes the attack at the browser and at the application.

munotes.in363

Cross-Site Request Forgery

A worked example, framed defensively

An assessor reviews an application for CSRF, using a test account.

  • A change-email action is performed by a simple state-changing request, with no anti-forgery token and the session cookie having no SameSite restriction. Finding: CSRF vulnerability on a sensitive action; a malicious page could change a logged-in victim's email, then trigger a password reset to it. Fix: add anti-forgery tokens and set a restrictive SameSite.
  • A funds-transfer action requires an anti-forgery token. Recorded as correctly defended: a forged request lacks the token and is rejected.
  • The most sensitive actions do not require re-authentication. Recommendation: add it for changing email and for large transfers, as defence in depth.
  • The assessor verifies the fix by confirming that a cross-site request without the token, and (with SameSite set) without the cookie, is rejected.

The report explains the distinction from XSS explicitly, because the client asked "isn't this the same as the scripting issue?", and the answer, that CSRF causes an action without reading the response and needs no flaw in the target, only reliance on the cookie alone, is exactly the distinction this chapter teaches.

What beginners get wrong

  • Confusing CSRF with XSS. XSS runs the attacker's script on the target site (and can do anything, including read data and steal the token); CSRF makes the browser send a request to the target site and cannot read the response.
  • Thinking the attacker steals the token. They do not; they exploit that the browser attaches the cookie automatically, so the request is authenticated without the attacker knowing the token.
  • Believing the attacker reads the response. They cannot, because same-origin protections prevent their site reading it; CSRF is for state-changing actions, not data theft.
  • Assuming a target flaw is needed. CSRF needs no flaw in the target beyond authenticating a request on the cookie alone; it exploits normal browser behaviour.
  • Relying on SameSite alone or tokens alone. Use both for defence in depth, plus re-authentication for the most sensitive actions.
  • Performing sensitive actions on easily-forged simple requests. Require an unpredictable token the attacker's site cannot read.

Quick revision

  • CSRF: a malicious site causes a logged-in victim's browser to send a state-changing request to the target site; the browser automatically attaches the session cookie, so the request is authenticated and processed as intended.
  • The attacker does not know the token and cannot read the response (same-origin protections), so CSRF is for state-changing actions, not data theft.
  • Against XSS: XSS runs the attacker's script on your site (powerful: reads data, steals the token); CSRF makes your browser send a request to your site (narrower: causes an action). XSS needs a target flaw; CSRF needs only reliance on the cookie alone.
  • Defences: anti-forgery tokens (an unpredictable per-session secret the attacker's site cannot read, required on state-changing requests) and SameSite cookies (the cookie is not sent cross-site), plus re-authentication for sensitive actions and origin checks. Use tokens and SameSite together.
munotes.in364

Cross-Site Request Forgery

Test yourself

  1. Explain the mechanism of cross-site request forgery.

A logged-in victim's browser holds a valid session cookie for a target site. The victim visits a malicious page that causes their browser to send a state-changing request to the target site; because the request goes to that site, the browser automatically attaches the session cookie, so the request arrives authenticated and the target processes it as though the victim intended it. The attacker thereby causes an action on the victim's account without knowing the session token.

  1. Why can CSRF change state but not read data?

Because although the browser sends the forged request with the cookie and receives the response, the attacker's page is on a different origin and the browser's same-origin protections prevent it from reading that response. So the attacker can cause an action, such as a transfer or a settings change, where causing it is the goal, but cannot see returned data, which is why CSRF targets state-changing actions rather than data theft.

  1. Distinguish cross-site request forgery from cross-site scripting.

Cross-site scripting runs the attacker's script on the target site in the victim's browser, giving full control on the page including reading the response, stealing the token and reading data, and it requires an XSS flaw in the target. Cross-site request forgery makes the victim's browser send a request to the target site and cannot read the response, so it only causes state-changing actions, and it needs no flaw in the target beyond the target authenticating requests on the session cookie alone.

  1. How does an anti-forgery token defeat CSRF?

The target site includes in each state-changing request a secret token unique to the user's session and unpredictable, and requires it to be present and correct before acting. The attacker's site, being on a different origin, cannot read this token because of same-origin protections, so it cannot include it in a forged request, which is therefore rejected even though the session cookie was attached automatically.

  1. How does the SameSite cookie attribute mitigate CSRF, and why combine it with tokens?

A restrictive SameSite attribute causes the browser not to attach the session cookie to cross-site requests, so a request forged by another site arrives without the cookie and is not authenticated, defeating the attack at the browser level. It is combined with anti-forgery tokens for defence in depth, so that the attack is blocked both at the browser, by withholding the cookie, and at the application, by requiring a token the attacker cannot supply, in case either measure is absent or bypassed in some context.

Contents This chapter on its own page

munotes.in365

Chapter Seventy-Seven

Session Defences in Full

Syllabus topic Module 2, "Session Hijacking and Token Security: ... prevention mechanisms like secure flags and HTTPS"

In one line

Securing a session is a set of measures, each closing a specific attack: strong random tokens (prediction), HTTPS everywhere with Secure and HttpOnly (sniffing and script theft), regeneration at login (fixation), SameSite and anti-forgery tokens (request forgery), expiry and rotation (limiting a stolen token), and server-side authority (manipulation).

In examination wording: comprehensive session management combines high-entropy token generation, transport encryption with appropriate cookie attributes, token regeneration on authentication and privilege change, cross-site request forgery protections, session expiry and inactivity timeout, and server-side storage of authoritative data, so that each identified attack against the session is prevented or its impact limited.

The block assembled

The block introduced the attacks and their individual defences across several chapters. This chapter is the assembly, because the examinable and professional answer to "how do you secure a session" is not one measure but the complete set, and the value of assembling them is seeing that each closes a different route and that omitting any one leaves that route open.

The mapping, which is the chapter in one table:

AttackDefence
Prediction (weak tokens)Strong, high-entropy tokens from a secure source
Sniffing (unencrypted)HTTPS everywhere, and the Secure cookie flag
Theft via script (XSS)The HttpOnly cookie flag (and fixing the XSS)
Fixation (planted token)Regenerate the token at login and on privilege change
Cross-site request forgerySameSite cookies and anti-forgery tokens
Cookie manipulationKeep authoritative data server-side; sign any cookie values
Any stolen tokenShort expiry, inactivity timeout, rotation; re-authentication for sensitive actions

A site is only session-secure if it has all of these, and a common finding is a site with several and not all, believing itself protected. The block exists to make the set complete.

The defences, as one checklist

Generate strong tokens. Long, unpredictable, from a cryptographically secure random source, so prediction is infeasible. Set once in the framework and correct thereafter.

Encrypt the whole session. HTTPS on every request, not just the login, so the token is never sent in the clear; and set the Secure flag so the browser withholds the cookie from any unencrypted request.

Hide the token from script. Set HttpOnly, so a cross-site-scripting flaw cannot read the session cookie; hold session tokens in HttpOnly cookies rather than script-readable storage; and fix XSS flaws (the coming chapters), because HttpOnly protects the token but not the rest.

Regenerate at login and privilege change. Issue a new token when the user authenticates and when their privileges rise, so a token known or captured beforehand becomes useless, defeating fixation.

Defend against request forgery. Set a restrictive SameSite, so the cookie is not sent cross-site, and require an anti-forgery token on state-changing requests, so a forged request lacks a value the attacker cannot supply.

munotes.in366

Session Defences in Full

Keep authority on the server. Store the user's identity, role and any trust-bearing value in the server-side session and look them up; never trust them from the cookie; sign any value that must live in a cookie. This defeats manipulation.

Limit the life of a token. Apply an inactivity timeout (the session ends after a period of no activity) and an absolute timeout (the session ends after a maximum duration regardless), so a stolen token is useful only briefly. Invalidate the session fully on logout, server-side, so the token points to nothing. Consider rotation of the token periodically during a long session.

Re-authenticate for sensitive actions. Require the password again for the most damaging operations (changing email, large transfers), so that a hijacked session cannot perform them unchallenged, which limits the damage of any token compromise that slips through.

Bind and monitor where appropriate. Some applications bind a session to attributes such as a consistent client, and monitor for anomalies (a session suddenly used from a new location or device), raising an alert or requiring re-authentication. This is defence in depth for high-value sessions.

Why "all of them" is the answer

The examinable synthesis: the defences are independent, each closing a route the others do not, so the security of the session is the security of its weakest missing measure.

  • A site with HTTPS, Secure and HttpOnly but weak tokens is hijacked by prediction.
  • A site with strong tokens and HTTPS but no HttpOnly is hijacked via XSS.
  • A site with everything but no regeneration at login is vulnerable to fixation.
  • A site with everything but no CSRF defence allows forged actions.
  • A site with everything but a token that never expires turns any single theft into permanent access.

So the correct answer to "how do you secure a session" is the whole checklist, and the correct assessment finding is which measures are missing, each mapped to the attack it would have prevented. That mapping is the block's contribution and the shape of a strong examination answer.

A worked example, framed defensively

An assessor produces the session-security section of a report, applying the checklist.

  • Tokens are strong and random. Good.
  • HTTPS is used everywhere, but the session cookie lacks Secure and HttpOnly. Findings: sniffing exposure on any HTTP endpoint, and script-theft exposure given a known XSS flaw. Fix: set both flags.
  • The token is not regenerated at login. Finding: fixation. Fix: regenerate at authentication and on privilege change.
  • No SameSite and no anti-forgery tokens on state-changing actions. Finding: cross-site request forgery. Fix: set SameSite and add tokens.
  • The role is read from a cookie. Finding: cookie manipulation and broken access control. Fix: move it server-side.
  • The session never times out. Finding: a stolen token is useful indefinitely. Fix: inactivity and absolute timeouts, and server-side invalidation on logout.
munotes.in367

Session Defences in Full

The report presents the findings as the checklist with the gaps marked, each gap mapped to its attack, and closes by noting that the application had strong tokens and HTTPS and was nonetheless hijackable five different ways, which is the block's thesis: session security is a set, not a single measure.

What beginners get wrong

  • Believing one or two measures secure the session. The defences are independent; the session is only as secure as the weakest missing one.
  • Encrypting the login only. The token travels with every request; HTTPS everywhere, with Secure, is required.
  • Setting flags but keeping weak tokens or no regeneration. Cookie flags close sniffing, script theft and forgery, not prediction or fixation.
  • Reading identity or role from the cookie. Authoritative data must live on the server and be looked up.
  • Never expiring sessions. A token that lives forever turns a single theft into permanent access; apply inactivity and absolute timeouts and invalidate on logout server-side.
  • Omitting re-authentication for sensitive actions. It is the control that limits the damage of any token compromise that slips through.

Quick revision

  • Session security is a set, each measure closing one route: strong random tokens (prediction); HTTPS everywhere + Secure (sniffing); HttpOnly (script theft); regenerate at login/privilege change (fixation); SameSite + anti-forgery tokens (request forgery); server-side authoritative data, signed cookie values (manipulation); inactivity + absolute timeouts, logout invalidation, rotation (limit a stolen token); re-authentication for sensitive actions (limit damage); optional binding and anomaly monitoring for high-value sessions.
  • The defences are independent: the session is only as secure as its weakest missing measure, so the complete checklist is the answer and an assessment reports which measures are absent, each mapped to its attack.

Test yourself

  1. Give the full set of session defences, each mapped to the attack it prevents.

Strong high-entropy tokens prevent prediction; HTTPS everywhere with the Secure flag prevents sniffing; the HttpOnly flag prevents script theft of the token; regenerating the token at login and privilege change prevents fixation; SameSite cookies and anti-forgery tokens prevent cross-site request forgery; keeping authoritative data server-side and signing any cookie values prevents cookie manipulation; and expiry, inactivity timeout, logout invalidation and rotation, together with re-authentication for sensitive actions, limit the impact of any stolen token.

  1. Why is the answer to "how do you secure a session" the whole checklist rather than a single measure?

Because the defences are independent, each closing a route the others do not, so the security of the session equals the security of its weakest missing measure. A site can have strong tokens and HTTPS and still be hijacked through a missing HttpOnly flag, a lack of token regeneration, or an absent cross-site request forgery defence, so only the complete set closes every route.

munotes.in368

Session Defences in Full

  1. Why must the session token be regenerated at login even if all the cookie flags are set?

Because the cookie flags close sniffing, script theft and request forgery but not fixation, which exploits the server keeping the same token across the change from anonymous to authenticated. Regenerating the token at login issues a fresh token and abandons any that was planted beforehand, so a token an attacker fixed in the victim's browser becomes useless once the victim authenticates.

  1. Why is an expiry and inactivity timeout important even with every other defence in place?

Because no set of preventive measures is perfect, and any token that is nonetheless compromised remains usable for as long as it is valid. Inactivity and absolute timeouts, together with server-side invalidation on logout and periodic rotation, ensure that a stolen token is useful only briefly rather than granting indefinite access, so they limit the impact of any compromise that slips through.

  1. What does storing the user's role in the server-side session rather than in a cookie protect against, and why?

It protects against cookie manipulation, because a cookie is under the client's control and any trust-bearing value in it, such as a role, can be altered by the user to gain unauthorised access. Keeping the role and other authoritative data in the server-side session and looking them up means the client cannot change them, so the server's decisions rest on data the client cannot forge.

Contents This chapter on its own page

munotes.in369

Chapter Seventy-Eight

The Web Server Against the Web Application

Syllabus topic Module 2, "Web Server Vulnerabilities and Hardening Techniques: Study common web server misconfigurations"

In one line

A website is two things stacked: the web server (the platform that delivers it) and the web application (the site's own code). They fail in different ways, are fixed by different people, and this block is the platform, while the blocks after it are the code.

In examination wording: web security concerns two distinct layers, the web-server platform comprising the server software, operating system and supporting components, and the web application comprising the site's own program logic; platform vulnerabilities arise chiefly from misconfiguration and unpatched software, while application vulnerabilities arise from flaws in the application's code, and the two require different remediation.

The two layers

Picture a running website as a stack:

  • At the bottom, the operating system.
  • On it, the web-server software that receives requests and sends responses, together with the interpreters, libraries and modules that run the application.
  • On top, the web application: the site's own code, the logic that decides what each request does.

The platform is everything except the application's own code: the server software and its configuration, the operating system, the modules and runtimes. The application is the code the site's developers wrote.

They fail in fundamentally different ways:

  • The platform fails through misconfiguration (a wrong setting, a default left on, an unnecessary feature enabled) and unpatched software (a known flaw in the server or a module, with a CVE and a vendor fix). These are the subject of this block.
  • The application fails through flaws in its code: injection, broken access control, cross-site scripting, the logic errors of the OWASP block. These are the subject of the blocks after.

Why the distinction matters

Three practical consequences make the distinction worth insisting on.

Different owners, different fixes. Platform issues are usually fixed by the operations or infrastructure team, by changing configuration or applying a patch. Application issues are fixed by the developers, by changing code. Directing a platform finding to the developers, or an application finding to operations, wastes time and often results in neither fixing it. A report that does not distinguish them is harder to act on.

Different discovery methods. Platform issues are often found by scanning (a vulnerability scanner identifies the server version and its known CVEs, and detects misconfigurations like directory listing), while application issues require testing the application's logic, which scanners do poorly. A tester uses different techniques for the two.

The striking fact about platform security. Most platform breaches are not exotic. They are a default left on, a folder left listable, a patch left unapplied, a sample application never removed. The application blocks that follow contain clever attacks; this block is mostly about not leaving the obvious open, which is unglamorous and is where a large share of real compromises begin. That contrast, sophisticated application attacks against mundane platform mistakes, is itself worth teaching, because it corrects the beginner's assumption that security is mainly about clever attacks.

munotes.in370

The Web Server Against the Web Application

What belongs to each

To make the split concrete, a classification of the issues in this and the following blocks:

IssueLayer
Directory listing enabledPlatform (server configuration)
Default or sample files presentPlatform
Verbose error pagesPlatform (though applications can cause them too)
Unpatched server or modulePlatform
Missing security headersPlatform (server configuration)
Directory traversalPlatform, usually, though the application can cause it
SQL injectionApplication (code)
Cross-site scriptingApplication (code)
Broken access controlApplication (code)
Session management flawsApplication (code)

The boundary is occasionally blurred, directory traversal can arise from either a server misconfiguration or application code, and verbose errors from either, so a tester notes which in each case. But the split is clear enough to organise the work and the report, and clear enough that the fix's owner is usually obvious.

The shared responsibility in hosted environments

A modern complication worth naming, because it changes who fixes what. Many applications run on platforms the organisation does not fully control: managed hosting, cloud services, containers. In these, the platform responsibility is shared between the provider and the customer, and a security failure can fall on either side.

  • The provider typically secures the underlying infrastructure and, in managed services, patches the platform.
  • The customer typically remains responsible for configuration (the settings they choose), for their application code, and often for keeping their own components patched.

The common failure is a customer assuming the provider secures something the provider does not, leaving a gap. So in a hosted environment a tester and a defender must establish the shared-responsibility boundary for that service, which determines who owns each finding. This connects to the OWASP supply-chain and misconfiguration categories later, and it is why cloud misconfiguration (a customer-side setting left insecure) is such a common real finding.

A worked example, framed defensively

An assessor reviews a website and sorts findings by layer, which is the first thing the report does.

  • Directory listing is enabled on an uploads folder, exposing files. Platform: a server configuration setting. Owner: operations. Fix: disable listing.
  • The server runs an outdated version with a known critical CVE. Platform: unpatched software. Owner: operations. Fix: patch.
  • The search feature is vulnerable to SQL injection. Application: a code flaw. Owner: developers. Fix: parameterised queries.
  • A cloud storage area is publicly readable due to a misconfigured access setting. Platform, customer-side in the shared-responsibility model: the provider secures the infrastructure, the customer chose the setting. Owner: whoever manages the cloud configuration. Fix: restrict access.
munotes.in371

The Web Server Against the Web Application

The report groups these into platform and application sections, assigns each an owner, and, for the cloud finding, states the shared-responsibility boundary so it is clear the customer, not the provider, must fix it. This sorting is the chapter's practical contribution: before fixing anything, know which layer it is on and who owns it.

What beginners get wrong

  • Merging the platform and the application. Directory listing and default files are server configuration; SQL injection is application code. Different owners, different fixes, different discovery methods.
  • Thinking platform security is about clever attacks. It is mostly about not leaving the obvious open: defaults, listable folders, unapplied patches, sample files.
  • Sending findings to the wrong team. A platform finding to developers, or an application finding to operations, stalls the fix.
  • Assuming a scanner finds application flaws. Scanners are good at platform issues (versions, misconfigurations) and poor at application logic, which needs manual testing.
  • Misreading the shared-responsibility boundary in hosted environments. Assuming the provider secures something they do not leaves a gap; establish the boundary for each service.
  • Treating a blurred case as unclassifiable. Directory traversal and verbose errors can come from either layer; note which in each case rather than ignoring the split.

Quick revision

  • A website is platform (server software, operating system, modules, and their configuration) plus application (the site's own code).
  • Platform fails through misconfiguration and unpatched software; application fails through code flaws (injection, broken access control, XSS, session issues).
  • The distinction matters for owner (operations against developers), discovery (scanning against manual testing), and because platform breaches are mostly mundane (defaults, listable folders, unapplied patches), not clever.
  • This block is the platform; the OWASP and injection blocks are the application.
  • In hosted environments the platform responsibility is shared: the provider secures the infrastructure, the customer owns configuration and code; establish the boundary per service, as customer-side misconfiguration is a common finding.

Test yourself

  1. What is the difference between a web-server vulnerability and a web-application vulnerability?

A web-server, or platform, vulnerability lies in the server software, operating system, modules or their configuration, arising from misconfiguration or unpatched software, such as directory listing being enabled or an outdated server version. A web-application vulnerability lies in the site's own code, such as SQL injection or broken access control. They occupy different layers of the stack.

  1. Why does the distinction matter in practice?

Because the two have different owners, platform issues fixed by operations through configuration or patching and application issues fixed by developers through code, so misdirecting a finding stalls its remediation; because they are discovered differently, platform issues largely by scanning and application issues by manual testing; and because it corrects the assumption that security is mainly clever attacks, since most platform breaches stem from mundane defaults, listable folders and unapplied patches.

munotes.in372

The Web Server Against the Web Application

  1. Why is it said that platform security is mostly about not leaving the obvious open?

Because the majority of real platform breaches result from unremarkable oversights: a default setting left on, a folder left listable, a sample application never removed, or a patch never applied, rather than from sophisticated attacks. The application blocks contain the clever techniques; the platform block is largely about closing these obvious and common exposures.

  1. How does the shared-responsibility model complicate platform security in hosted environments?

Because responsibility for the platform is divided between the provider and the customer, with the provider typically securing the underlying infrastructure and the customer remaining responsible for the configuration they choose, their application code and often patching their own components. A common failure is the customer assuming the provider secures something it does not, leaving a gap, so the shared-responsibility boundary for each service must be established to determine who owns each finding.

  1. How should a report handle a finding whose layer is genuinely blurred, such as directory traversal?

By determining in the specific case whether it arises from server configuration or from the application's code, since directory traversal can come from either, and classifying and assigning ownership accordingly. The boundary is clear enough in most cases to organise the report into platform and application sections and assign each finding to the team that can fix it, and blurred cases are resolved by noting the actual source rather than left unclassified.

Contents This chapter on its own page

munotes.in373

Chapter Seventy-Nine

Common Web Server Misconfigurations

Syllabus topic Module 2, "Web Server Vulnerabilities and Hardening Techniques: Study common web server misconfigurations"

In one line

Web servers are compromised through the same handful of misconfigurations again and again: directory listing on, default and sample files present, verbose errors, unnecessary features enabled, weak administrative access, and missing security headers. Each is a setting, and each has a one-line fix.

In examination wording: common web-server misconfigurations include enabled directory listing, retained default and sample content, verbose error messages, unnecessary enabled modules and methods, exposed or default-secured administrative interfaces, and absent security response headers; each unnecessarily increases the attack surface or discloses information, and each is remedied by configuration.

Directory listing

When a folder has no index page and the server is configured to list its contents, a visitor who navigates to that folder sees every file in it, including files that were never linked and were never meant to be public: backups, configuration files, uploads, exports, old versions.

The exposure is that the folder becomes a public file browser. A /backup/ folder with listing on may hand over a database dump; an /uploads/ folder may expose documents; a source folder may expose code and secrets.

Fix: disable automatic directory listing globally, so a folder with no index page returns an error rather than its contents. It is a single server setting and one of the most common findings.

Default and sample files

Servers, frameworks and applications ship with default content: sample applications, test pages, documentation, example scripts, and default administrative consoles. Left in place after deployment, these are a problem for several reasons:

  • They identify the software and version (the fingerprinting of the enumeration block), because the default page is recognisable.
  • They may contain known vulnerabilities that the main application does not, and are a target precisely because they are often forgotten.
  • Default administrative consoles may have default credentials, the enumeration block's finding.
  • Sample scripts have historically contained deliberately-insecure examples that are exploitable in production.

Fix: remove all default, sample and documentation content from production, and remove or secure default administrative interfaces. A deployment should ship only what the application needs.

Verbose error messages

When something goes wrong, a server or application can return an error page, and a verbose one is a gift to an attacker. It may disclose:

  • the software and version (fingerprinting again);
  • internal file paths, revealing the server's directory structure;
  • database details or fragments of queries, which aid SQL injection;
  • stack traces showing the application's internal structure and the technologies in use.

Verbose errors are useful to developers and dangerous in production, and they can come from either the platform or the application (the blurred case from the previous chapter).

Fix: return generic error pages to users in production, disclosing nothing, and keep the detailed error information in server-side logs where developers can read it. Never show a stack trace or a database error to a user.

munotes.in374

Common Web Server Misconfigurations

Unnecessary features, modules and methods

Every enabled feature is attack surface. A server running modules the site does not use, interpreters that are not needed, or supporting HTTP methods beyond those the application requires, is exposed for no benefit.

Specific cases:

  • Unused modules and extensions: each is code that can have vulnerabilities and can be attacked, for no benefit if unused.
  • Unnecessary HTTP methods: methods that allow writing or other operations, enabled where the application only needs to read, can permit unintended actions.
  • Unneeded interpreters and runtimes: a language runtime enabled where nothing uses it is surface for no purpose.

Fix: disable everything not needed. This is the least-privilege principle applied to the platform: enable only the features, modules and methods the application actually uses, and turn off the rest. Every disabled feature is one fewer thing to attack, misconfigure or patch.

Weak or exposed administrative access

Management interfaces, the server's own administrative console, a database administration tool, an application's admin panel, are high-value targets, and two failures are common:

  • Reachable from the internet when they should be restricted to internal or management networks. An admin panel on the public internet is a target for credential attacks around the clock.
  • Default or weak credentials, the enumeration block's recurring finding.

Fix: restrict administrative interfaces to trusted networks (a management network, a VPN, or specific addresses), require strong authentication and multi-factor on them, and change all default credentials. An administrative interface should not face the public internet.

Missing security response headers

Servers can send response headers that instruct the browser to enforce protections, and their absence is a common finding because they are opt-in and easily overlooked. The main ones, treated fully in the hardening chapter:

  • HSTS, which forces the browser to use HTTPS, preventing downgrade to plain HTTP.
  • Content-Security-Policy, which restricts what the page may load and run, mitigating cross-site scripting.
  • X-Content-Type-Options, which stops the browser guessing content types in unsafe ways.
  • Frame controls, which prevent the page being embedded to trick users (clickjacking).
  • Referrer-Policy, which limits what is disclosed when navigating away.

Fix: set the appropriate security headers, which is server or application configuration.

The pattern, and the checklist

Every item shares the shape from the platform chapter: a setting that unnecessarily exposes something, with a configuration fix. The checklist:

MisconfigurationExposesFix
Directory listing onEvery file in unindexed foldersDisable directory listing
Default/sample filesVersion, known flaws, default credentialsRemove them; secure admin consoles
Verbose errorsVersions, paths, queries, stack tracesGeneric error pages; detail to logs
Unnecessary featuresAttack surface for no benefitDisable unused modules, methods, runtimes
Weak/exposed admin accessA high-value entry pointRestrict to trusted networks; strong auth; no defaults
Missing security headersBrowser protections not enforcedSet the headers
munotes.in375

Common Web Server Misconfigurations

Because these are configuration and common, they are the bulk of a web-server assessment, and the fixes are cheap. The next chapter takes directory traversal in depth, and the hardening chapter assembles all of this into a baseline.

A worked example, framed defensively

An assessor reviews a web server's configuration.

  • Directory listing is on for /files/, exposing an old export. Finding. Fix: disable listing; move exports out of the web root.
  • The framework's default welcome page is still present, naming the exact version. Finding. Fix: remove it; patch the framework.
  • Errors return full stack traces with database details. Finding. Fix: generic error pages; detail to logs.
  • The server has unused modules enabled and permits HTTP methods the site does not use. Finding. Fix: disable the unused modules and methods.
  • The admin console is reachable from the internet on default-shaped credentials. Serious finding. Fix: restrict to the management network, require multi-factor, change credentials.
  • No security headers are set. Finding. Fix: set HSTS, Content-Security-Policy and the others.

The report is a configuration checklist with the gaps marked, and the assessor notes that every one is a setting and none required an exploit to find, which is the platform block's thesis: the platform is compromised through the mundane, and the fixes are cheap.

What beginners get wrong

  • Underrating these because they are not clever. They are the mundane findings that cause most platform breaches; the previous chapter's point.
  • Leaving directory listing on. It turns an unindexed folder into a public file browser; disable it globally.
  • Leaving default and sample content. It fingerprints the software, may carry known flaws, and may have default credentials; remove it.
  • Showing verbose errors in production. They disclose versions, paths and queries; generic pages for users, detail to logs.
  • Enabling features "just in case". Every enabled feature is attack surface; disable the unused.
  • Exposing admin interfaces to the internet. Restrict them to trusted networks with strong authentication and no defaults.
  • Omitting security headers. They are opt-in and easily overlooked; set them.

Quick revision

  • Common misconfigurations, each a setting with a one-line fix: directory listing on (exposes files; disable), default/sample files (fingerprint, flaws, default credentials; remove), verbose errors (versions, paths, queries; generic pages, detail to logs), unnecessary features/modules/methods (attack surface; disable the unused), weak or exposed admin access (restrict to trusted networks, strong auth, no defaults), missing security headers (set HSTS, CSP, and the others).
  • All share the platform pattern: a setting exposes something, and configuration fixes it. They are common and cheap to fix, hence the bulk of a web-server assessment.
munotes.in376

Common Web Server Misconfigurations

Test yourself

  1. What does enabled directory listing expose, and how is it fixed?

When a folder has no index page and listing is enabled, the server displays the folder's entire contents, including files never linked or meant to be public such as backups, configuration files and exports, effectively turning the folder into a public file browser. It is fixed by disabling automatic directory listing globally, so an unindexed folder returns an error rather than its contents.

  1. Why are default and sample files a security problem, and what should be done with them?

Because they identify the software and version, may contain known vulnerabilities that the main application does not, may include default administrative consoles with default credentials, and have historically contained deliberately-insecure example code exploitable in production. They should be removed entirely from production, and any default administrative interfaces removed or secured.

  1. Why are verbose error messages dangerous in production, and what is the fix?

Because they can disclose the software and version, internal file paths, database details or query fragments, and stack traces revealing the application's structure and technologies, all of which aid an attacker. The fix is to return generic error pages to users that disclose nothing while keeping the detailed error information in server-side logs for developers.

  1. Why should unnecessary features, modules and HTTP methods be disabled?

Because every enabled feature is attack surface: it is code that can contain vulnerabilities and be attacked, and an unnecessary HTTP method may permit unintended operations, all for no benefit if unused. Disabling everything the application does not actually use applies least privilege to the platform, reducing what can be attacked, misconfigured or need patching.

  1. What two failures commonly affect administrative interfaces, and how are they remedied?

They are commonly reachable from the internet when they should be restricted to internal or management networks, exposing them to continuous credential attacks, and they are commonly left on default or weak credentials. They are remedied by restricting the interfaces to trusted networks such as a management network or VPN, requiring strong authentication with multi-factor, and changing all default credentials, so that an administrative interface never faces the public internet unprotected.

Contents This chapter on its own page

munotes.in377

Chapter Eighty

Directory Traversal

Syllabus topic Module 2, "Web Server Vulnerabilities and Hardening Techniques: ... directory traversal attacks"

In one line

Directory traversal escapes the folder a web server is meant to serve from, by putting "go up a level" sequences into input that the application turns into a file path, reaching files elsewhere on the server. The robust fix is not to build file paths from user input at all.

In examination wording: directory traversal, or path traversal, is an attack that accesses files outside the intended directory by supplying input containing path-navigation sequences that the application incorporates into a file path without adequate validation, disclosing or manipulating files the application never intended to expose.

The mechanism, at the level of the path

A web server is meant to serve files from one folder, the web root, and its subfolders. A request for a document maps, somehow, to a file within that area.

The vulnerability arises when the application builds a file path from user input without checking it. If a parameter names a file to serve, and the application takes that parameter and turns it into a path, then an attacker can include the "go up a level" sequence (written ../ on most systems) to climb out of the intended folder.

At the level of the path: if the application intends to serve files from a documents folder, and it constructs the path by joining that folder with the user's parameter, then a parameter packed with repeated ../ sequences walks up out of the documents folder, up out of the web root, and back down to a file elsewhere on the server, a configuration file, a password file, application source, anything the server's account can read.

The essence, and the reason the fix is what it is: the server followed a path it should never have been asked to construct. It did what it was told, and it was told to build a path from input that should not have been trusted to name a path.

What it exposes

The consequence is reading, and sometimes writing, files outside the intended area:

  • Configuration files, which may contain database credentials and keys (the stored-credentials finding from earlier chapters, reached through the web).
  • Source code, revealing the application's logic and its other flaws.
  • System files, such as the file listing user accounts.
  • Logs and other data.

In the worst cases, where the flaw allows writing rather than only reading, an attacker can place a file that leads to further compromise. Even read-only, the disclosure of configuration and source is serious, because it hands the attacker credentials and a map of the application.

Why filtering is the wrong fix

The tempting fix is to filter the input: reject any parameter containing ../. This is fragile, and understanding why is the chapter's transferable lesson.

munotes.in378

Directory Traversal

An attacker who controls the input can encode the dangerous sequence in ways that a naive filter does not recognise but the system still interprets as "go up": different encodings, doubled or mixed separators, and platform-specific variations. A filter that blocks the plain ../ is bypassed by a form of it the filter did not anticipate but the file system still resolves. This is a recurring theme: filtering a dangerous pattern is weak when the attacker controls the encoding, which the input-validation chapter states as a general principle and which appeared already in the Log4Shell case.

So filtering is a supplementary measure at best. The robust fixes work at a different level.

The robust fixes

The fixes remove the ability to build an arbitrary path from input, rather than trying to catch the bad inputs:

Do not build file paths from user input at all. The strongest fix. Instead of taking a filename from the user and turning it into a path, map the user's choice to a fixed set of allowed files: the user supplies an identifier, and the application looks up which file that identifier corresponds to from a list it controls. The raw input never becomes part of a path, so there is no path to traverse. This removes the class entirely and is the preferred approach.

Canonicalise and validate. Where a path must be derived from input, resolve it to its canonical, absolute form (which collapses all the ../ sequences and encodings into a definite path) and then confirm that the result still lies inside the intended folder before serving it. Anything that resolves outside the folder is rejected. The key is that the check happens after resolution, on the final path, so no encoding trick survives, because they have all been resolved away.

Run the server with least privilege. So that even a successful traversal reaches only what the server's account can read, which should be very little. This does not prevent the traversal but limits its reach, and it is defence in depth: the web-server account should not be able to read the whole file system.

The combination, and the order: map inputs to allowed files where possible; where a path must be built, canonicalise and validate against the intended folder; and run with least privilege as a backstop. Filtering ../ is at most a supplementary measure and never the primary defence.

A worked example, framed defensively

An assessor reviews a document-download feature, using a test account and the application's own files.

  • The feature takes a file parameter and joins it with the documents folder to build a path. Supplying a value with repeated ../ sequences resolves to a file outside the documents folder, and the assessor confirms (on a test file they placed for the purpose, not on real sensitive files) that the traversal reaches outside the intended area. Finding: directory traversal.
  • Testing a filter: the application blocks a plain ../, but an encoded form is not blocked and still traverses. Finding: the filter is bypassable, illustrating why filtering is not the fix.
  • The web-server account can read broad areas of the file system. Finding: no least privilege, so a traversal reaches more than it should.
munotes.in379

Directory Traversal

Recommendations, in order: map the file parameter to an allow-list of documents so no path is built from input (the class-removing fix); where any path is derived from input, canonicalise and validate it against the intended folder; and run the server with least privilege so a traversal reaches little. The assessor demonstrates the flaw on a planted test file rather than by reading the client's actual sensitive files, which is the minimum needed to prove the finding.

What beginners get wrong

  • Thinking filtering ../ is the fix. Attackers encode the sequence in forms a naive filter misses; filtering is supplementary, and the robust fix is not to build paths from input.
  • Building a file path directly from a user parameter. That is the flaw; map inputs to allowed files instead.
  • Validating before resolving. A check on the raw input misses encoded traversal; canonicalise first, then validate the resolved path against the intended folder.
  • Ignoring least privilege. A web-server account that can read the whole file system turns a traversal into a broad disclosure; restrict it.
  • Treating read-only traversal as minor. Disclosure of configuration and source hands over credentials and a map of the application, which is serious.
  • Confusing the layer. Traversal can arise from server configuration or application code; note which, and fix at the right level.

Quick revision

  • Directory traversal escapes the web root by putting "go up a level" (../) sequences into input the application turns into a file path, reaching files elsewhere: configuration (credentials), source, system files.
  • The essence: the server followed a path it should never have been asked to construct from untrusted input.
  • Filtering ../ is fragile, because the attacker can encode the sequence in forms a naive filter misses but the system still resolves; it is supplementary at best.
  • Robust fixes, in order: map inputs to a fixed allow-list of files so no path is built from input (removes the class); canonicalise and validate any derived path against the intended folder, checking after resolution; and run the server with least privilege so a traversal reaches little.

Test yourself

  1. Explain directory traversal at the level of the path.
munotes.in380

Directory Traversal

The application builds a file path by combining an intended folder with user-supplied input, and the input contains "go up a level" sequences such as ../. These cause the constructed path to climb out of the intended folder and the web root and back down to a file elsewhere on the server, so the server serves a file outside the area it was meant to, such as a configuration file or source code, because it followed a path built from untrusted input.

  1. What does a successful directory traversal expose, and why is even read-only traversal serious?

It exposes files outside the intended area: configuration files that may contain database credentials and keys, application source code revealing logic and other flaws, system files such as the account list, and logs. Even read-only, this is serious because disclosing configuration hands over credentials and disclosing source provides a map of the application and its weaknesses, materially advancing an attack.

  1. Why is filtering the ../ sequence a weak defence?

Because an attacker who controls the input can encode the "go up" sequence in forms a naive filter does not recognise, such as alternative encodings, doubled or mixed separators, or platform-specific variants, which the file system still resolves as traversal. Blocking the plain sequence is therefore bypassed by a form the filter did not anticipate, which is why pattern filtering is at most supplementary when the attacker controls the encoding.

  1. What is the strongest fix for directory traversal, and why?

Not building file paths from user input at all: mapping the user's choice to a fixed set of allowed files, so the user supplies an identifier that the application looks up against a list it controls, and the raw input never becomes part of a path. This removes the class entirely, because with no path constructed from input there is nothing to traverse.

  1. When a path must be derived from input, how should it be validated, and what backstop limits the damage?

The derived path should be resolved to its canonical absolute form, which collapses all navigation sequences and encodings into a definite path, and then checked to confirm it still lies inside the intended folder, rejecting anything that resolves outside; the validation must occur after resolution so no encoding trick survives. Running the server with least privilege is the backstop, so that even a successful traversal reaches only the little the server's account can read.

Contents This chapter on its own page

munotes.in381

Chapter Eighty-One

Patch Management

Syllabus topic Module 2, "Web Server Vulnerabilities and Hardening Techniques: ... patch management practices"

In one line

Patch management is the discipline that ensures known fixes are actually applied, promptly and everywhere. Its hard parts are not installing an update but knowing what you run, prioritising by severity and exposure, and applying without breaking, because the exploitation window closes for you only when you patch.

In examination wording: patch management is the systematic process of identifying, acquiring, testing, and applying software updates that remediate known vulnerabilities; its effectiveness depends on maintaining an accurate inventory of software and versions, tracking vendor advisories, prioritising by severity and exposure, and deploying reliably across the estate, since a vulnerability remains exploitable until each affected system is patched.

Why patch management is the control that matters most

The vulnerability-lifecycle chapter of Module 1 established the single most important fact about real-world compromise: the great majority of attacks exploit known, patched vulnerabilities on systems that were not updated, not zero-days. The exploitation window, it said, closes for a given user only when that user patches.

Patch management is the discipline that closes that window fast. It is unglamorous, and it prevents more harm than any clever control, which is why it is worth a chapter of its own rather than a line in the hardening list. A perfectly hardened server running an unpatched component with a public exploit is compromised; a modestly configured server that is fully patched denies the attacker the known flaws.

The mistake is to think patch management is "install updates". Installing is the easy last step. The discipline is everything around it, and the following sections are the hard parts.

Know what you run: the inventory

You cannot patch what you do not know you have. This is the first and most-failed requirement, and it connects to the whole book's theme of inventory.

An organisation must maintain an accurate inventory of every system, every piece of software, and every version, including:

  • servers, operating systems and their versions;
  • web servers, application frameworks, interpreters and their versions;
  • components and libraries the applications depend on, including indirect dependencies (the supply-chain problem of the Log4Shell case: you cannot patch a library you did not know your application contained);
  • the forgotten systems the reconnaissance block kept surfacing: the old server, the test host, the appliance nobody owns.

Without this inventory, an advisory for a critical flaw arrives and the organisation cannot answer "do we run this, and where?", which is exactly the paralysis the Log4Shell case described. A software bill of materials, a machine-readable list of the components in each application, turns that multi-day question into a query, which is why it is a patch-management tool and not just paperwork.

Track the advisories

Knowing what you run is only useful if you also learn when a fix exists for it. So patch management includes tracking vendor advisories and vulnerability feeds for the software in the inventory, so that a new fix is learned of quickly rather than discovered when the flaw is exploited. This is the CVE and advisory machinery of Module 1 applied operationally: subscribe to the sources, and match new advisories against the inventory to find what applies to you.

munotes.in382

Patch Management

Prioritise: not everything at once

An organisation cannot test and apply every patch instantly, so it must prioritise, and the prioritisation combines the factors the CVSS chapters established:

  • Severity, from the CVSS score: how bad the flaw is intrinsically.
  • Exposure: is the affected system internet-facing, does it process untrusted input, is it reachable by attackers? A critical flaw on an internet-facing server is an emergency; the same flaw on an isolated internal system is not.
  • Exploitation status: is the flaw being actively exploited in the wild? A flaw under mass exploitation jumps the queue regardless of severity, which the CVSS chapters flagged as the factor teams most often omit.

So the order of work is not "highest CVSS first" but "highest risk first", combining severity with exposure and active exploitation. An internet-facing system with a flaw being exploited now is patched before a higher-severity flaw on an isolated system nobody is attacking.

Apply without breaking

The reason patching is not instant is that a patch can break something, and an organisation that has been burned by a bad update becomes reluctant to patch, which is itself a security problem. So patch management includes:

  • Testing patches, where feasible, in a non-production environment before applying to production, to catch breakage.
  • Staged rollout, applying to a subset first and watching, then to the rest, so a problem affects few systems.
  • A rollback plan, so a bad patch can be reversed.
  • Maintenance windows and change control, balancing the urgency of the fix against the disruption of applying it, with the balance tilting toward speed for critical, exposed, actively-exploited flaws.
  • Automation, because manual patching across a large estate is where systems get missed. Automated patch deployment, with the testing and staging above, is how an organisation patches promptly and completely.

The tension to acknowledge honestly: speed against stability. Patching fast reduces the exploitation window but risks breakage; patching slowly avoids breakage but leaves the window open. The resolution is to patch critical, exposed flaws quickly (accepting some risk of breakage, mitigated by staging and rollback) and to apply less urgent patches on a regular tested cycle.

Handle what cannot be patched

Some systems cannot be patched promptly or at all: an appliance with no available update, a legacy system a critical application depends on, an embedded device. For these, patch management includes compensating controls, the idea from the defender's-mirror chapter:

munotes.in383

Patch Management

  • Isolate the unpatchable system on its own segment, so a flaw in it cannot spread.
  • Restrict access to it as tightly as possible.
  • Monitor it closely, since it cannot be fixed.
  • Plan its replacement, because an unpatchable system is a liability with a limited safe life.

An honest patch-management programme records what cannot be patched and what compensating controls protect it, rather than pretending everything is current.

A worked example, framed defensively

An assessor reviews an organisation's patch management.

  • There is no accurate inventory of software and versions, and no software bill of materials for the applications. The most serious finding, because it means the organisation cannot know what a new advisory applies to. Recommendation: build and maintain an inventory, including component dependencies.
  • Advisories are not systematically tracked; the team learns of flaws ad hoc. Recommendation: subscribe to and monitor advisories for the inventory.
  • Patching is done on a fixed monthly cycle regardless of severity, so a critical internet-facing flaw waits weeks. Finding: prioritise by risk, patching critical exposed flaws out of cycle.
  • An unpatchable legacy appliance runs on the main network with no compensating controls. Finding: isolate it, restrict and monitor it, and plan replacement.
  • Patching is manual, and several systems are found running outdated versions the team believed were patched. Finding: automate, so systems are not missed.

The report's theme is that installing updates was never the problem; the gaps are inventory, tracking, prioritisation, and reliable application, which are the discipline of patch management. The assessor establishes them by reviewing process and records, not by exploiting the unpatched flaws.

What beginners get wrong

  • Thinking patch management is "install updates". Installing is the easy last step; the discipline is inventory, advisory tracking, prioritisation and reliable application.
  • Not maintaining an inventory. You cannot patch what you do not know you run, including indirect dependencies; a software bill of materials is the tool.
  • Patching by CVSS alone. Prioritise by risk: severity plus exposure plus active exploitation, so an exploited internet-facing flaw jumps the queue.
  • Patching everything on one fixed cycle. Critical exposed flaws need out-of-cycle speed; a rigid cycle leaves urgent windows open.
  • Not testing or staging. A bad patch that breaks production makes the team reluctant to patch; test, stage, and keep a rollback plan.
  • Pretending everything is patchable. Unpatchable systems need compensating controls (isolate, restrict, monitor) and a replacement plan, recorded honestly.

Quick revision

  • Patch management closes the exploitation window, which shuts for a system only when it is patched; most real attacks exploit known, patched flaws on unpatched systems.
  • It is more than installing updates. The hard parts: inventory (you cannot patch what you do not know you run, including indirect dependencies; a software bill of materials helps), tracking advisories for the inventory, prioritising by risk (severity + exposure + active exploitation, not CVSS alone), and applying reliably (test, stage, roll back, automate, balancing speed against stability).
  • Unpatchable systems get compensating controls, isolate, restrict, monitor, and a replacement plan, recorded honestly.
munotes.in384

Patch Management

Test yourself

  1. Why is patch management described as the control that prevents the most harm?

Because the great majority of real compromises exploit known, already-patched vulnerabilities on systems that were not updated, rather than zero-days, and the exploitation window closes for a given system only when that system is patched. Patch management is the discipline that closes that window promptly, so despite being unglamorous it prevents more harm than any single clever control.

  1. Why can patch management not be reduced to "install updates"?

Because installing is the easy final step, while the discipline consists of the hard parts around it: maintaining an accurate inventory of what is run, including indirect component dependencies; tracking advisories to learn when fixes exist; prioritising which patches to apply first; and applying them reliably across an estate without causing breakage. A failure in any of these leaves systems unpatched even when updates are available.

  1. Why is an accurate inventory the first requirement, and what tool assists it for application components?

Because you cannot patch what you do not know you run, so when an advisory for a critical flaw arrives, an organisation without an inventory cannot answer whether and where it runs the affected software, which is the paralysis seen in the Log4Shell case. A software bill of materials, a machine-readable list of the components in each application including indirect dependencies, assists by turning that question into a query.

  1. How should patches be prioritised, and why is CVSS score alone insufficient?

By risk, combining the CVSS severity with the exposure of the affected system, whether it is internet-facing and reachable by attackers, and whether the flaw is being actively exploited in the wild. CVSS alone is insufficient because a medium-severity flaw on an internet-facing system under active exploitation presents more real risk than a higher-severity flaw on an isolated system nobody is attacking, so exposure and exploitation status reorder the queue.

  1. How should systems that cannot be patched be handled?

With compensating controls and a plan: isolating the unpatchable system on its own network segment so a flaw cannot spread, restricting access to it as tightly as possible, monitoring it closely since it cannot be fixed, and planning its replacement because it is a liability with a limited safe life. An honest patch-management programme records what cannot be patched and the controls protecting it rather than assuming everything is current.

Contents This chapter on its own page

munotes.in385

Chapter Eighty-Two

Hardening and the Security Response Headers

Syllabus topic Module 2, "Web Server Vulnerabilities and Hardening Techniques: ... hardening strategies"

In one line

Hardening is the discipline of reducing a server's attack surface to the minimum the site needs and locking down what remains, following a published benchmark and re-checking for drift. The security response headers are part of it: instructions the server sends the browser to enforce protections.

In examination wording: server hardening is the systematic reduction of attack surface and enforcement of secure configuration, comprising removal of unnecessary components, secure settings, least privilege, timely patching, and the setting of HTTP security response headers that instruct the browser to enforce protections such as transport security, content restrictions and framing controls.

Hardening as synthesis

Hardening is not a new technique but the assembly of the block into one practice, so this chapter is deliberately a synthesis. Its principle, stated in the platform chapter and repeated here as the organising idea: reduce the attack surface to the minimum the site needs, and lock down what remains.

Everything in the block feeds it:

  • Remove default and sample content, disable directory listing, use generic errors (the misconfiguration chapter).
  • Disable unnecessary features, modules and methods (the misconfiguration chapter).
  • Restrict and secure administrative interfaces (the misconfiguration chapter).
  • Fix path handling and run with least privilege (the traversal chapter).
  • Keep everything patched (the patch-management chapter).
  • Set the security headers (this chapter).

Hardening is doing all of these deliberately, from a checklist, so that the server offers an attacker almost nothing.

The hardening baseline

A concrete baseline, assembling the block:

  • Remove the unnecessary: default files, sample applications, documentation, unused modules, interpreters and HTTP methods.
  • Disable directory listing and use generic error pages.
  • Run with least privilege: the server's account has only the access it needs, so a flaw reaches little.
  • Secure administrative access: restrict to trusted networks, strong authentication and multi-factor, no defaults.
  • Enforce transport security: HTTPS everywhere with a valid certificate and modern configuration (the encryption chapters).
  • Set the security response headers (below).
  • Keep everything patched (the patch-management chapter).
  • Follow a published hardening benchmark for the specific server and operating system, rather than inventing the list, because such benchmarks are maintained by security bodies and cover far more than one person would remember.
  • Re-check for drift, because configuration changes over time as features are enabled for projects and settings are altered, so a hardened server does not stay hardened without periodic re-checking.

The last two points matter: hardening is not a one-off. A benchmark provides completeness, and drift-checking provides durability, because a server hardened once and never re-checked slowly loosens.

The security response headers

MU's "hardening strategies" includes the HTTP security headers, which the misconfiguration chapter listed and this chapter explains. They are instructions the server puts in its responses telling the browser to enforce protections, and their power is that the enforcement happens in the browser, defending the user even against flaws the server did not fully prevent. Each maps to an attack.

munotes.in386

Hardening and the Security Response Headers

HSTS (Strict-Transport-Security). Tells the browser to use HTTPS only for this site, for a stated period, so it will not connect over plain HTTP even if asked. This prevents downgrade attacks (forcing a user onto HTTP to sniff) and stops the browser sending a first request over HTTP that could be intercepted. It reinforces the transport-encryption defence of the sniffing block.

Content-Security-Policy (CSP). Tells the browser what the page is allowed to load and run: which sources of scripts, styles and other content are permitted. Its main value is mitigating cross-site scripting: a strong policy that only allows scripts from trusted sources means that even if an attacker injects a script, the browser refuses to run it because it is not from an allowed source. CSP is defence in depth for XSS, treated fully in the XSS-defence chapter, and it is one of the most valuable headers.

X-Content-Type-Options. Tells the browser not to guess content types (not to "sniff" the type of a response), which prevents attacks that rely on the browser interpreting a file as a different, more dangerous type than intended.

Frame controls (X-Frame-Options / frame-ancestors in CSP). Control whether the page may be embedded in a frame on another site. This prevents clickjacking, an attack that embeds the target page invisibly over a decoy so the victim's clicks land on the hidden real page, performing actions they did not intend. Restricting framing to the site itself defeats it.

Referrer-Policy. Controls how much of the current address is disclosed to another site when the user navigates away, limiting leakage of potentially sensitive information in URLs.

Others worth knowing: headers that control which browser features a page may use, and cross-origin isolation headers for advanced protection.

The set, as a table:

HeaderEnforcesAttack mitigated
HSTSHTTPS onlyDowngrade, sniffing
Content-Security-PolicyAllowed content sourcesCross-site scripting (defence in depth)
X-Content-Type-OptionsNo type guessingContent-type confusion
Frame controlsFraming restrictionsClickjacking
Referrer-PolicyReferrer disclosure limitsInformation leakage in URLs

Setting them is configuration, and their absence is a common finding because they are opt-in, so a hardening baseline includes them and an assessment checks for them.

A worked example, framed defensively

An assessor produces the hardening section of a report, assembling the block.

  • Default files present, directory listing on, verbose errors: findings from the misconfiguration chapter. Fix per that chapter.
  • Server runs with broad privileges; unused modules enabled. Findings. Fix: least privilege, disable the unused.
  • No security headers are set. Findings: no HSTS (downgrade exposure), no CSP (no XSS defence in depth), no frame controls (clickjacking exposure), and the others. Fix: set the headers.
  • No hardening benchmark is followed, and configuration has drifted since deployment (a module was re-enabled for a project and left on). Findings: adopt a benchmark and schedule drift-checking.
  • Patching is behind (the patch-management chapter's findings).
munotes.in387

Hardening and the Security Response Headers

The report presents the hardening baseline with the gaps marked, and recommends adopting a published benchmark and periodic re-checking so the server is hardened durably rather than once. The theme is the block's: the platform is secured by reducing surface and locking down the rest, from a checklist, and keeping it that way.

What beginners get wrong

  • Treating hardening as one-off. Configuration drifts; follow a benchmark for completeness and re-check periodically for durability.
  • Inventing the hardening list. Published benchmarks cover far more than one person remembers; use them.
  • Omitting the security headers. They are opt-in and commonly missing; each closes an attack, and setting them is configuration.
  • Thinking CSP is only for XSS purists. It is one of the most valuable headers, providing defence in depth against XSS by refusing to run scripts from disallowed sources.
  • Forgetting clickjacking. Frame controls prevent the page being embedded to trick users; set them.
  • Hardening the configuration but leaving it unpatched. Hardening and patching are both required; a hardened but unpatched server is still compromised.

Quick revision

  • Hardening = reduce attack surface to the minimum needed and lock down the rest, assembling the block: remove the unnecessary, disable listing and use generic errors, least privilege, secure admin access, HTTPS everywhere, set security headers, patch, follow a published benchmark, and re-check for drift.
  • Security response headers instruct the browser to enforce protections: HSTS (HTTPS only; downgrade/sniffing), Content-Security-Policy (allowed content; XSS defence in depth), X-Content-Type-Options (no type guessing), frame controls (clickjacking), Referrer-Policy (URL leakage). Setting them is configuration; their absence is a common finding.
  • Hardening is not one-off: a benchmark gives completeness, drift-checking gives durability.

Test yourself

  1. What is the principle of hardening, and why is this chapter described as a synthesis?

The principle is to reduce a server's attack surface to the minimum the site needs and to lock down what remains. It is a synthesis because it assembles the whole web-server block into one deliberate practice: removing unnecessary content and features, disabling listing and using generic errors, running with least privilege, securing administrative access, enforcing HTTPS, setting security headers, and patching, all from a checklist.

  1. What do the security response headers do, and why is enforcement in the browser valuable?

They are instructions the server places in its responses telling the browser to enforce protections, such as using HTTPS only, restricting what content the page may load and run, and controlling framing. Enforcement in the browser is valuable because it defends the user directly, including against flaws the server did not fully prevent, for example refusing to run an injected script that is not from an allowed source.

munotes.in388

Hardening and the Security Response Headers

  1. What does Content-Security-Policy mitigate, and how?

It mitigates cross-site scripting, as defence in depth. It tells the browser which sources of scripts and other content are permitted, so that even if an attacker manages to inject a script into the page, the browser refuses to execute it because it does not come from an allowed source, limiting the impact of an XSS flaw the application did not prevent.

  1. What is clickjacking, and which header prevents it?

Clickjacking embeds the target page, often invisibly, over a decoy page so that a victim's clicks actually land on the hidden real page, causing them to perform actions they did not intend. It is prevented by frame controls, such as X-Frame-Options or the frame-ancestors directive of Content-Security-Policy, which restrict whether and where the page may be embedded in a frame, so it cannot be framed by an attacker's site.

  1. Why is hardening not a one-off task, and what two practices address this?

Because a server's configuration drifts over time as features are enabled for projects and settings are changed, so a server hardened once slowly loosens. Following a published hardening benchmark addresses completeness, ensuring the configuration covers far more than any individual would remember, and periodic re-checking for drift addresses durability, catching changes that have loosened the configuration since it was last hardened.

Contents This chapter on its own page

munotes.in389

Chapter Eighty-Three

The OWASP Top 10: What It Is and How It Changed

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: Examine major web application vulnerabilities (OWASP Top 10)"

In one line

The OWASP Top 10 is the security world's agreed list of the ten most critical kinds of web-application weakness, published by a respected non-profit and refreshed every few years. It is a checklist and a shared language, not a ranking of your particular site.

In examination wording: the OWASP Top 10 is a consensus document, published by the Open Worldwide Application Security Project, identifying the most critical categories of web-application security risk, intended as an awareness and prioritisation aid for developers and testers; it is revised periodically, and the 2021 and 2025 editions are the recent versions.

Why a top-ten list exists

Web applications fail in a huge variety of ways, and a beginner told to "secure this application" has no idea where to start. OWASP's answer is to gather data from across the industry and publish the ten categories that cause the most, and the most serious, real breaches.

That does three things, and naming them is the examinable purpose of the list:

  • It tells a developer what to prioritise, since the list is ordered by prevalence and impact.
  • It gives testers a systematic checklist, so that a web-application test covers the common serious categories rather than wherever attention happened to fall.
  • It gives everyone a shared vocabulary: "that is an injection issue" or "that is broken access control" means the same to two strangers, which makes findings communicable.

It is the single most widely used document in application security, which is why MU names it directly and why this block is organised around it.

Two cautions the block keeps

It is a list of categories, not of your bugs. The Top 10 is an industry aggregate; your particular application may have none of one category and many of another. Reading it as "these are our problems" is wrong; it is "these are the kinds of problem to check for". A finding is your bug; the category is where it fits.

It changes. The list is revised every few years as the threat landscape moves, so there is no single permanent Top 10. An examiner may have the 2021 edition or the 2025 edition, and a professional keeps current, so a student should know both recent editions and, importantly, what moved between them, because the movement is itself a lesson.

The current list: OWASP Top 10:2025

The 2025 edition is the current released version as of this book, and since the course runs from Academic Year 2026-27 it is what a current practitioner uses:

  1. A01:2025 Broken Access Control (users acting outside their permissions)
  2. A02:2025 Security Misconfiguration (insecure settings, defaults, verbose errors)
  3. A03:2025 Software Supply Chain Failures (risk from third-party components and the build pipeline)
  4. A04:2025 Cryptographic Failures (weak or missing encryption, poor key or password handling)
  5. A05:2025 Injection (untrusted input treated as code or commands)
  6. A06:2025 Insecure Design (the design itself is unsafe)
  7. A07:2025 Authentication Failures (weak login, session or credential handling)
  8. A08:2025 Software or Data Integrity Failures (trusting code or data whose integrity is unverified)
  9. A09:2025 Security Logging and Alerting Failures (breaches unseen because nothing is logged or watched)
  10. A10:2025 Mishandling of Exceptional Conditions (errors and edge cases handled unsafely)
munotes.in390

The OWASP Top 10: What It Is and How It Changed

The previous list: OWASP Top 10:2021

The 2021 edition is still the one the prescribed CEH textbook and most question banks use, so a student must know it too:

  1. A01:2021 Broken Access Control
  2. A02:2021 Cryptographic Failures
  3. A03:2021 Injection
  4. A04:2021 Insecure Design
  5. A05:2021 Security Misconfiguration
  6. A06:2021 Vulnerable and Outdated Components
  7. A07:2021 Identification and Authentication Failures
  8. A08:2021 Software and Data Integrity Failures
  9. A09:2021 Security Logging and Monitoring Failures
  10. A10:2021 Server-Side Request Forgery (SSRF)

What changed, and why the change is a lesson

Comparing the two editions teaches how the threat landscape moves, which is more valuable than either list alone:

  • Broken Access Control stayed at number one. It is consistently the most common serious web-application weakness, which is why it leads both editions and gets the first deep chapter.
  • Supply-chain risk rose. The 2021 category "Vulnerable and Outdated Components" grew into 2025's "Software Supply Chain Failures", a broader category reflecting years of attacks through third-party dependencies and build pipelines, the Log4Shell lesson elevated. This is the clearest single change and it has its own chapter.
  • SSRF was folded in. Server-Side Request Forgery, its own category in 2021, is grouped under Broken Access Control in 2025, because it is fundamentally about a request reaching somewhere it should not.
  • New framings appeared. "Mishandling of Exceptional Conditions" (2025) recognises unsafe error and edge-case handling as a category of its own.

The movement itself is the point: security is not static, and last year's checklist is not this year's. A student who can state one significant change and what it reflects is demonstrating exactly the currency the subject demands.

The thread through most of them

Preview of the block's synthesis, developed in the input-validation chapter. Look across both lists and a pattern emerges: most categories reduce to trusting input or context that should have been checked.

  • Injection trusts input as code.
  • Broken Access Control trusts the user to ask only for what they may have.
  • Cross-site scripting (an injection form) trusts input as page content.
  • SSRF trusts a user-supplied address.
  • Supply-chain failures trust borrowed code.

Again and again the failure is trusting something that should have been validated or verified, which is why two defences recur across the whole list: input validation and correct access control. The rest is specific: encrypt properly, configure securely, keep components patched, log and watch, and design safely from the start.

munotes.in391

The OWASP Top 10: What It Is and How It Changed

How this block maps

Several categories were covered before the block, which is why the following chapters are fewer than ten:

CategoryWhere in this book
Broken Access Controlits own chapter (84), plus SSRF (92)
Security Misconfigurationthe web-server block (79, 82), summarised in 85
Cryptographic Failuresthe cryptography block (54 to 60), summarised in 85
Supply-Chain / Vulnerable Componentsits own chapter (86)
Injectionits own chapters (87, and SQL injection 94 to 98)
Cross-site scriptingits own chapters (88, 89)
Insecure Design, Authentication Failureschapter 90
Integrity, Logging, Exceptional Conditionschapter 91
Input validation (the thread)chapter 93

A worked example, framed defensively

A reviewer sorts the findings of an authorised web-application assessment into the OWASP Top 10 categories, to show how the list is used as a shared vocabulary and checklist, at concept level.

  • A finding that a logged-in user could reach another user's records by altering a request is sorted as Broken Access Control (A01), the category that leads both lists. The reviewer notes it is the most common category, not a rare one.
  • A finding that an input field was handled so that supplied text could be treated as a command is sorted as Injection (A05 in 2025), an instance of the thread that runs through the list: trusting input that should have been validated.
  • A finding that the application fetched a user-supplied address server-side is sorted, on the 2025 list, under Broken Access Control, because server-side request forgery folded into A01, whereas on the 2021 list it was its own category, A10. The same finding, two editions, two placements, which is exactly why the reviewer records which edition the report uses.
  • A finding that a borrowed component was outdated is sorted as Software Supply Chain Failures (A03 in 2025), the category that rose between editions, illustrating that the list itself changes.
  • The reviewer observes that the sorted findings cluster around trusting input or context and around access control, the block's thread, so the recurring remediations are input validation and correct server-side authorisation.

The categorisation gives the client a shared vocabulary and a checklist, shows that the placement depends on the edition, and surfaces the thread. The reviewer sorts and communicates findings to help the client fix them; nothing is exploited.

What beginners get wrong

  • Treating the Top 10 as a ranking of their own bugs. It is an industry list of categories; your application's actual risks may be distributed quite differently.
  • Learning only one edition. The list changes; know 2021 and 2025, because either may be examined and both are current in different places.
  • Thinking injection is the only category worth studying. Broken access control leads both lists and is more common; the whole list matters.
  • Missing the thread. Most categories reduce to trusting input or context; input validation and access control recur across the list.
  • Ignoring what changed. The movement between editions (supply chain rising, SSRF folding in) is itself the lesson that security is not static.
munotes.in392

The OWASP Top 10: What It Is and How It Changed

Quick revision

  • The OWASP Top 10 is a consensus list of the most critical web-application risk categories, published by OWASP and refreshed periodically. Purpose: prioritisation, a systematic checklist, and a shared vocabulary.
  • Two cautions: it is categories, not your bugs, and it changes (know 2021 and 2025).
  • 2025: Broken Access Control, Security Misconfiguration, Software Supply Chain Failures, Cryptographic Failures, Injection, Insecure Design, Authentication Failures, Software/Data Integrity Failures, Security Logging and Alerting Failures, Mishandling of Exceptional Conditions.
  • Key changes to 2025: Broken Access Control still leads; supply-chain risk rose (from Vulnerable Components); SSRF folded into access control.
  • The thread: most categories reduce to trusting input or context; the recurring defences are input validation and correct access control.

Test yourself

  1. What is the OWASP Top 10, and what three purposes does it serve?

A consensus document published by OWASP identifying the most critical categories of web-application security risk, revised periodically. It serves to tell developers what to prioritise, since it is ordered by prevalence and impact; to give testers a systematic checklist so a web-application test covers the common serious categories; and to provide a shared vocabulary so that findings can be communicated unambiguously.

  1. Why is the Top 10 a list of categories rather than of an application's actual bugs?

Because it is an industry-wide aggregate of the most common and serious kinds of weakness, not an analysis of any particular application, whose real risks may be distributed quite differently, with none of one category and many of another. It should be read as the kinds of problem to check for, with a finding being the specific bug and the category being where it fits.

  1. Which category leads both the 2021 and 2025 editions, and what does that indicate?

Broken Access Control, meaning users being able to act outside their permissions. Its position at the top of both editions indicates that it is consistently the most common and serious category of web-application weakness, which is why it is examined first among the categories and treated in its own chapter.

  1. Give one significant change from the 2021 to the 2025 edition and what it reflects.

The 2021 category "Vulnerable and Outdated Components" grew into 2025's broader "Software Supply Chain Failures", reflecting years of attacks through third-party dependencies and build pipelines, the lesson of incidents like Log4Shell elevated to a top category. Also acceptable: Server-Side Request Forgery, its own 2021 category, was folded into Broken Access Control in 2025.

munotes.in393

The OWASP Top 10: What It Is and How It Changed

  1. What single thread runs through most of the Top 10 categories, and which two defences follow from it?

That most categories reduce to trusting input or context that should have been checked: injection trusts input as code, broken access control trusts the user's request, cross-site scripting trusts input as page content, SSRF trusts a supplied address, and supply-chain failures trust borrowed code. The two recurring defences are input validation, treating all input as untrusted and neutralising it for its context, and correct server-side access control.

Contents This chapter on its own page

munotes.in394

Chapter Eighty-Four

A01: Broken Access Control

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: Examine major web application vulnerabilities (OWASP Top 10)"

In one line

Broken access control is users being able to do things they should not: read another user's data, reach an administrative function, or act beyond their role. It is the most common serious web-application weakness, and it happens because applications check who you are (authentication) and forget to check what you may do (authorisation).

In examination wording: broken access control is the failure to enforce restrictions on what authenticated users are permitted to do, allowing access to unauthorised functionality or data; it encompasses insecure direct object references, missing function-level authorisation, and privilege escalation, and it is remedied by enforcing authorisation server-side on every request against the acting user's permissions.

Authentication against authorisation

The distinction is the key to the whole category, so state it precisely.

  • Authentication answers "who are you?". It is the login: verifying identity.
  • Authorisation (access control) answers "what are you allowed to do?". It is the check, on each action, that this identity is permitted this operation on this resource.

They are different, and applications routinely get the first right and the second wrong: a user logs in correctly (authentication works), and then the application fails to check, on each request, that they may do what they are asking (authorisation fails). Because logging in feels like the security step, the per-request authorisation check is forgotten, which is exactly why this category is the most common.

The rule the category enforces: being logged in is not permission to do anything; every action must be authorised against the acting user's permissions.

The forms it takes

Insecure direct object references. The application exposes a reference to an object (a record, a file, an account) and acts on it without checking the user is allowed that object. The classic case: a page shows your account statement at an address containing your account number, and changing the number to another account's shows their statement, because the application returned the record named in the request without checking it belonged to the requester. This is horizontal access control failing (the horizontal-escalation idea from the system-hacking block), and it is extremely common.

Missing function-level access control. An administrative or privileged function is protected only by not being linked for ordinary users, rather than by an actual check. An ordinary user who discovers or guesses the address of the admin function can use it, because the application never verifies that the caller is an administrator; it merely did not show them the link. Hiding a function is not protecting it, exactly as the search-engine reconnaissance chapter said hiding a page is not protecting it.

Privilege escalation through access control. A user manipulates a request (a role in a cookie, a parameter, the previous chapter's cookie manipulation) to gain higher privileges, because the application trusts client-supplied data about what the user may do.

munotes.in395

A01: Broken Access Control

Metadata and method manipulation. Changing the HTTP method, or other request metadata, to reach an operation the application authorises for one method but not another.

Forced browsing. Directly requesting resources or functions the user was never meant to reach, which succeeds when authorisation is not enforced on them.

Why it is the most common category

Three reasons a student should be able to give, because they explain the category's persistence:

  • Authorisation is per-action, so it is easy to miss one. A large application has hundreds of actions, each needing an authorisation check, and missing the check on any one is a vulnerability. Authentication is one place; authorisation is everywhere, so it is more often incomplete.
  • The default is often "allow". Where authorisation is not enforced, the action frequently proceeds, so a forgotten check fails open. Secure design makes the default "deny", so a forgotten check fails closed.
  • It is invisible in normal use. A user testing their own account never triggers the flaw, because they are accessing their own data; it only appears when someone accesses someone else's, which ordinary testing does not do. So the flaw ships undetected, which is why it is so common in production.

The defences

The fixes follow from the authentication-authorisation distinction:

Enforce authorisation on every request, server-side. Every action that touches a resource checks, on the server, that the acting user is permitted this operation on this specific resource. Not once at login, not in the browser, but on each request, on the server. This is the primary fix and it removes most of the category.

Deny by default. Design so that access is refused unless explicitly granted, so a forgotten check fails closed rather than open. This turns the "default allow" weakness into a "default deny" strength.

Do not rely on hiding. A function or resource is protected by an authorisation check, never by being unlinked or having an unguessable address. Hiding is not access control.

Use indirect references or verify ownership. Either do not expose direct object references (use identifiers that are looked up against the user's own resources), or, where a reference is exposed, verify on every access that the resource belongs to the requester. This closes insecure direct object references.

Do not trust client-supplied authorisation data. The user's role and permissions are held and checked server-side, never taken from a cookie or parameter (the cookie-manipulation fix), which closes the escalation-through-manipulation form.

Test for it deliberately. Because it is invisible in normal use, testing must specifically attempt to access other users' resources and privileged functions, with multiple test accounts, which is exactly what the flaw's invisibility requires.

munotes.in396

A01: Broken Access Control

A worked example, framed defensively

An assessor tests an application for broken access control, using two test accounts they control.

  • Logged in as test user A, changing an account_id in a URL to test user B's returns B's statement. Insecure direct object reference / broken access control: the application checked A was logged in but not that the account was A's. Fix: verify on every access that the account belongs to the acting user.
  • The address of an admin page is guessed; as an ordinary user, it loads and functions. Missing function-level access control: the function was hidden, not protected. Fix: enforce an administrator check on the function server-side.
  • A role in a cookie can be changed to elevate privileges. Privilege escalation through manipulation: the application trusts client data about the role. Fix: hold the role server-side.
  • The assessor confirms the fixes by attempting the same accesses and finding them refused with a proper authorisation error.

The report leads with this category because it is the most common and most serious, and the assessor establishes each finding by accessing resources between their own two test accounts, never a real user's data, which is the minimum and the ethical way to prove it.

What beginners get wrong

  • Confusing authentication with authorisation. Authentication is who you are; authorisation is what you may do. This category is authorisation failing after authentication succeeds.
  • Thinking being logged in is permission. Every action must be authorised against the acting user's permissions, on the server, on each request.
  • Protecting functions by hiding them. An unlinked or unguessable address is not access control; enforce a check.
  • Trusting client-supplied role or permission data. Hold and check them server-side; a role in a cookie can be changed.
  • Testing only your own account. The flaw is invisible in normal use; testing must attempt to reach other users' resources with multiple accounts.
  • Failing open. Where authorisation is not enforced the action often proceeds; design to deny by default so a forgotten check fails closed.

Quick revision

  • Broken access control = users doing what they should not (read others' data, reach admin functions, exceed their role); the most common serious web-application weakness, leading both OWASP editions.
  • The key distinction: authentication (who you are) against authorisation (what you may do). The category is authorisation failing after authentication succeeds.
  • Forms: insecure direct object references (act on a referenced object without checking ownership), missing function-level control (hidden, not protected, functions), privilege escalation (manipulating role/permission data), method manipulation, forced browsing.
  • Common because authorisation is per-action (easy to miss one), often fails open, and is invisible in normal use (you test your own account).
  • Defences: enforce authorisation server-side on every request against the acting user; deny by default; do not rely on hiding; verify ownership or use indirect references; hold roles server-side; test deliberately with multiple accounts.
munotes.in397

A01: Broken Access Control

Test yourself

  1. What is the difference between authentication and authorisation, and how does this category relate to it?

Authentication answers "who are you?", verifying identity at login, while authorisation answers "what are you allowed to do?", checking on each action that the identity is permitted the operation on the resource. Broken access control is the category in which authentication succeeds but authorisation fails: the user logs in correctly, and the application then fails to check, on each request, that they may do what they are asking.

  1. What is an insecure direct object reference?

It is when an application exposes a reference to an object, such as a record or account identifier, and acts on it without checking that the requesting user is allowed that object, so changing the reference in a request, for example another account's number in a URL, returns that other object. It is a failure of horizontal access control and one of the most common forms of the category.

  1. Why is protecting a function only by not linking it inadequate?

Because not linking a function hides it but does not protect it: an ordinary user who discovers or guesses the function's address can invoke it, since the application never verifies that the caller is authorised for it. Access control must be an enforced server-side check on the function, not the mere absence of a visible link, exactly as hiding a page does not make it private.

  1. Why is broken access control the most common serious web-application category?

Because authorisation must be enforced on every one of an application's many actions, so missing the check on any single action is a vulnerability, whereas authentication is one place; because it often fails open, proceeding when the check is absent; and because it is invisible in normal use, since a user accessing their own account never triggers it, so it ships to production undetected by ordinary testing.

  1. What is the primary defence, and why must access control be tested deliberately?

The primary defence is to enforce authorisation on every request, on the server, checking that the acting user is permitted the specific operation on the specific resource, with a deny-by-default design so a forgotten check fails closed. It must be tested deliberately because the flaw does not appear when a user accesses their own resources, so testing must specifically attempt to reach other users' data and privileged functions using multiple test accounts.

Contents This chapter on its own page

munotes.in398

Chapter Eighty-Five

Security Misconfiguration and Cryptographic Failures

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: Examine major web application vulnerabilities (OWASP Top 10)"

In one line

Two Top-10 categories are already familiar: Security Misconfiguration is the web-server block's mundane settings seen as an application risk, and Cryptographic Failures is the cryptography block's sound-primitives-used-wrongly seen the same way. This chapter places them in the OWASP frame.

In examination wording: Security Misconfiguration is the OWASP category covering insecure or default configuration across the application stack; Cryptographic Failures (formerly termed Sensitive Data Exposure) covers the absence or misuse of cryptography protecting data in transit and at rest; both are among the most prevalent categories and both are addressed by the configuration and cryptographic disciplines established earlier in this book.

Why these two are treated together and briefly

The OWASP block covers ten categories, and two of them the book has already taught thoroughly. Repeating them would waste the reader's time, and omitting them would leave the block incomplete, so this chapter does the right thing: it places them in the OWASP frame, points back to their full treatment, and adds only what is specific to seeing them as application risks. A student should be able to name each category, say where its full treatment is, and give the application angle.

Security Misconfiguration

In the OWASP frame. This category is insecure or default configuration anywhere in the application stack: the web server, the application framework, the database, the cloud services, the container. It is consistently one of the most prevalent categories, for the reason the web-server block gave: misconfigurations are mundane, produce no symptom, and are common.

Where its full treatment is. The web-server block: common misconfigurations (chapter 79), directory traversal (80), and hardening with the security headers (82). Everything there is this OWASP category, so the reader is referred to it rather than repeated.

The application-specific angle, which the web-server block did not fully cover:

  • Framework and application defaults: application frameworks ship with default settings, sample configurations and debug modes that are insecure in production. A debug mode left on can expose internal detail (the verbose-errors problem at the application level); a default secret key left unchanged undermines anything that depends on it.
  • Cloud and service configuration: the shared-responsibility misconfigurations, a storage area left public, an over-permissive access policy, a service exposed that should be internal. These are customer-side settings and a very common real finding.
  • Missing hardening at the application layer: the security headers (chapter 82) are set by the application or server; their absence is this category.
  • Verbose application errors: an application returning stack traces and internal detail to users, the application-layer form of verbose errors.

The fix, from the hardening chapter: a secure, minimal configuration across the whole stack, defaults changed, debug off in production, unnecessary features disabled, security headers set, following a benchmark and re-checked for drift. The application is part of the stack the hardening baseline covers.

munotes.in399

Security Misconfiguration and Cryptographic Failures

Cryptographic Failures

In the OWASP frame. This category, once called Sensitive Data Exposure, covers the absence or misuse of cryptography protecting sensitive data, in transit and at rest. The rename is instructive: it moved from describing the consequence (data exposed) to the cause (cryptography failing), which matches the cryptography block's thesis that failures are misuse rather than broken ciphers.

Where its full treatment is. The cryptography block: encoding against encryption against hashing (chapter 54), symmetric and asymmetric encryption (55), hash functions (56), password storage and salting (57), and cryptographic weaknesses (60). The catalogue of weaknesses in chapter 60, obsolete algorithms, fast hashes for passwords, missing salts, weak randomness, hard-coded keys, home-made schemes, is exactly this OWASP category.

The application-specific angle:

  • Sensitive data sent without encryption: personal data, credentials or financial information transmitted over plain HTTP, or an API not using TLS, which the sniffing block showed is captured in the clear. This is the commonest form and it maps to "encrypt in transit".
  • Sensitive data stored without encryption: personal or financial data in a database in plaintext, so a breach (through SQL injection, say) exposes it directly.
  • Passwords stored wrongly: the storage-model failures of chapter 57, unsalted, fast-hashed, encrypted or plaintext passwords, are this category in an application.
  • Weak transport configuration: obsolete TLS versions or weak cipher suites, the obsolete-algorithm weakness applied to the connection.
  • Secrets in the application: hard-coded keys and credentials (the reconnaissance and cryptographic-weaknesses chapters), which is this category and supply-chain-adjacent.

The fix, from the cryptography block: encrypt sensitive data in transit and at rest with sound, current algorithms used correctly, store passwords with a slow salted hash, use strong randomness, manage keys properly (not in code), and avoid obsolete algorithms and home-made schemes. And, upstream of all of it, minimise the sensitive data held, because data not stored cannot be exposed, which the confidentiality and reporting disciplines have emphasised.

Why placing them in the frame matters

The value of this chapter, beyond completeness, is that it shows the OWASP categories are not separate subjects from the rest of the book but the same material organised for web applications. Misconfiguration is the platform block; cryptographic failures are the cryptography block. A student who sees this understands that the Top 10 is a lens on knowledge they already have, which is the right way to hold it: not ten new things to memorise, but ten headings under which the book's material is filed for application security.

A worked example, framed defensively

An assessor reviews an application against these two categories.

munotes.in400

Security Misconfiguration and Cryptographic Failures

  • The framework is in debug mode in production, exposing stack traces and configuration. Security Misconfiguration. Fix: disable debug; generic errors; detail to logs.
  • A cloud storage bucket holding user uploads is publicly readable. Security Misconfiguration (customer-side). Fix: restrict access.
  • No security headers are set by the application. Security Misconfiguration. Fix: set them (chapter 82).
  • Personal data is sent to an internal API over plain HTTP. Cryptographic Failures. Fix: TLS in transit.
  • Passwords are stored as unsalted SHA-256. Cryptographic Failures. Fix: slow salted hash (chapter 57).
  • A hard-coded key is in the application's configuration in the repository. Cryptographic Failures / secrets management. Fix: secret-management system, key out of code.

The report files each under its OWASP category and points to the block that treats it fully, which is efficient and shows the client that these are known, well-understood classes with established fixes, not novel problems.

What beginners get wrong

  • Thinking these are new categories separate from the rest of the book. Misconfiguration is the web-server block; cryptographic failures are the cryptography block. The Top 10 organises material already covered.
  • Overlooking application-framework defaults. Debug modes, default keys and sample configurations left in production are Security Misconfiguration at the application level.
  • Missing customer-side cloud misconfiguration. Public buckets and over-permissive policies are a very common real finding under this category.
  • Reading "Cryptographic Failures" as broken ciphers. It is misuse: no encryption, weak storage, obsolete algorithms, hard-coded keys, exactly the cryptography block's thesis.
  • Forgetting to minimise sensitive data. Data not held cannot be exposed; minimisation is upstream of encryption.
  • Storing passwords with encryption or a fast hash. These are Cryptographic Failures; use a slow salted hash.

Quick revision

  • Security Misconfiguration: insecure or default configuration anywhere in the stack; full treatment in the web-server block (79, 80, 82). Application angle: framework debug modes and default keys, cloud/customer-side misconfiguration (public buckets), missing security headers, verbose application errors. Fix: secure minimal configuration across the stack, from a benchmark, re-checked for drift.
  • Cryptographic Failures (formerly Sensitive Data Exposure): absence or misuse of cryptography protecting data in transit and at rest; full treatment in the cryptography block (54 to 60). Application angle: data unencrypted in transit or at rest, passwords stored wrongly, weak TLS, hard-coded secrets. Fix: encrypt with sound current algorithms used correctly, slow salted password hashing, strong randomness, proper key management, and minimise sensitive data held.
  • Both show the Top 10 is a lens on material already covered, not ten new subjects.

Test yourself

  1. What does the Security Misconfiguration category cover, and where is its full treatment in this book?

It covers insecure or default configuration anywhere in the application stack, the web server, framework, database, cloud services and container, and is consistently among the most prevalent categories. Its full treatment is the web-server block: common misconfigurations, directory traversal, and hardening with the security response headers.

munotes.in401

Security Misconfiguration and Cryptographic Failures

  1. What is the application-specific angle on Security Misconfiguration that the web-server block did not fully cover?

Application-framework defaults such as debug modes left on in production and default secret keys left unchanged; cloud and customer-side misconfiguration such as publicly readable storage and over-permissive access policies; missing security headers set by the application; and verbose application-level errors exposing stack traces and internal detail. These are configuration failures at the application and service layer rather than the base server.

  1. Why was the OWASP category renamed from Sensitive Data Exposure to Cryptographic Failures, and what does the rename reflect?

Because it moved from naming the consequence, sensitive data being exposed, to naming the cause, cryptography being absent or misused. The rename reflects the reality that such exposures stem from cryptographic failures, missing encryption, weak storage, obsolete algorithms and poor key handling, which matches the principle that real cryptographic weakness is sound primitives used wrongly rather than broken ciphers.

  1. Give three application-level forms of Cryptographic Failures and their fixes.

Sensitive data sent without encryption, fixed by TLS in transit; passwords stored unsalted, fast-hashed, encrypted or in plaintext, fixed by a slow salted hash; and hard-coded keys or credentials in the application, fixed by moving them to a secret-management system out of the code. Weak TLS configuration and unencrypted data at rest are also acceptable, fixed by current algorithms correctly configured and encryption at rest.

  1. Why does this chapter treat two Top-10 categories briefly by pointing to earlier blocks?

Because both categories were already taught thoroughly, Security Misconfiguration in the web-server block and Cryptographic Failures in the cryptography block, so repeating them would waste the reader's time while omitting them would leave the OWASP block incomplete. Placing them in the OWASP frame and referring to their full treatment shows that the Top 10 is a lens organising material the book already covers, not ten new subjects to learn.

Contents This chapter on its own page

munotes.in402

Chapter Eighty-Six

Software Supply Chain Failures

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: Examine major web application vulnerabilities (OWASP Top 10)"

In one line

Your application is built mostly from code you did not write: libraries, frameworks, tools, and the pipeline that assembles them. Software supply chain failures are the risks in all of that borrowed code and machinery, and the defence begins with knowing what you depend on.

In examination wording: software supply chain failures encompass vulnerabilities and compromises arising from third-party components, dependencies (including indirect ones), and the build and distribution pipeline; the category rose to prominence as applications came to consist largely of borrowed code, and it is addressed by inventorying dependencies, tracking their vulnerabilities, verifying their integrity, and securing the build process.

Why this category rose

The OWASP overview chapter noted this as the clearest single change from 2021 to 2025: the 2021 category "Vulnerable and Outdated Components" grew into the broader 2025 "Software Supply Chain Failures". Understanding why it rose is the point.

Modern applications are not mostly your code. A typical application is a small amount of the developers' own logic sitting on a large foundation of borrowed code: frameworks, libraries for every common task, and their dependencies, and those dependencies' dependencies, often hundreds of components deep. The developers wrote perhaps a few per cent of the code that runs.

The consequence is that your security is largely the security of code you did not write and may not know you are running. A flaw in a widely-used library is a flaw in every application that includes it, directly or indirectly. This is the Log4Shell lesson stated as a category: a vulnerability in a logging library, buried as an indirect dependency in countless applications whose developers did not know they contained it, became everyone's emergency at once.

As attacks increasingly targeted this borrowed code and the pipelines that assemble it, OWASP broadened the category, because the risk is no longer only "you are running an outdated component" but the whole chain by which third-party code enters and runs in your application.

What the category covers

Broader than the old "outdated components", it includes:

Vulnerable and outdated components. The original core: using a library, framework or component with a known vulnerability, because it was not updated. This is the patch-management problem at the dependency level, and it is common because dependencies are numerous and easy to forget.

Indirect (transitive) dependencies. A component you chose depends on others you did not choose and may not know about, and a flaw in one of those is your flaw. Log4Shell's danger was largely that it was an indirect dependency, so organisations could not answer "do we run it?"

Compromised components. A dependency that is malicious, either because an attacker published a malicious package (sometimes named to resemble a legitimate one, "typosquatting"), or because a legitimate package was compromised at its source and a malicious version published to everyone who updates. This is the more insidious form: the code was not merely flawed but deliberately hostile.

munotes.in403

Software Supply Chain Failures

Dependency confusion. An attack in which an attacker publishes a public package with the same name as an organisation's internal private package, and the build system fetches the attacker's public one instead, pulling malicious code into the build.

Compromise of the build and distribution pipeline. The machinery that assembles and ships the software, the build servers, the pipeline, the update mechanism, is itself a target; compromising it injects malicious code into legitimately-signed releases, which then reach every user through the trusted update channel. This is the most damaging form, because the malicious code arrives with the authenticity of a genuine release.

The defence: know what you depend on

The recurring theme of the book, inventory, is the foundation here, and the phrase to carry is: you cannot secure, patch or assess a dependency you do not know you have.

Maintain a software bill of materials. A machine-readable inventory of every component in the application, including indirect dependencies, is the foundational control, exactly as the patch-management chapter said. It turns "do we run this vulnerable library?" from a multi-day investigation into a query, which is the difference between responding to the next Log4Shell in hours or in weeks.

Track and patch component vulnerabilities. Monitor advisories for the components in the inventory (dependency-scanning tools automate this against the bill of materials) and update vulnerable components promptly, which is patch management applied to dependencies.

Verify integrity. Check that components are genuine and unaltered, using signatures and checksums, so a compromised or substituted package is detected. This addresses the compromised-component and confusion forms.

Reduce and vet dependencies. Fewer dependencies means less surface: prefer well-maintained, widely-used components, avoid pulling in a large library for a trivial need, and remove unused dependencies. Vet significant new dependencies before adopting them.

Secure the build pipeline. Protect the build and distribution machinery as the high-value target it is, with access control, integrity checks on what it produces, and monitoring, so that a legitimate release cannot be poisoned. Configure the build system to prefer internal packages over public ones of the same name, closing dependency confusion.

Pin versions. Use specific, known versions of dependencies rather than automatically taking the latest, so a compromised new version is not pulled in automatically, balancing this against the need to update for security fixes.

A worked example, framed defensively

An assessor reviews an application's supply-chain posture.

  • There is no software bill of materials, so the organisation cannot enumerate its dependencies, direct or indirect. The foundational finding: when the next widely-exploited library flaw appears, they will not know if they run it. Recommendation: generate and maintain a bill of materials.
  • Dependency scanning is not performed, and several components have known vulnerabilities. Recommendation: scan against the inventory and update vulnerable components.
  • Component integrity is not verified; packages are pulled without checking signatures. Recommendation: verify signatures and checksums.
  • The build pipeline has weak access control and does not verify what it produces. Recommendation: secure the pipeline as a high-value target, and configure it to prefer internal packages (closing dependency confusion).
  • Dependencies are taken as "latest" automatically. Recommendation: pin versions, updating deliberately for security.
munotes.in404

Software Supply Chain Failures

The report's theme is that the application's security is largely the security of its borrowed code and its pipeline, and that the foundation of defending it is knowing what it contains, which the organisation currently cannot state. The assessor establishes this by reviewing the build configuration and dependency manifests, not by attacking the pipeline.

What beginners get wrong

  • Thinking the risk is only "outdated components". The category broadened to the whole chain: indirect dependencies, compromised and malicious packages, dependency confusion, and pipeline compromise.
  • Ignoring indirect dependencies. A flaw in a dependency of a dependency is your flaw, and it is the one you are least likely to know you have.
  • Not knowing what you depend on. You cannot patch or assess an unknown dependency; a software bill of materials is the foundational control.
  • Trusting packages without verifying integrity. Compromised or substituted packages are detected by signatures and checksums.
  • Overlooking the build pipeline. Compromising it injects malicious code into legitimately-signed releases that reach every user, the most damaging form.
  • Taking "latest" automatically. A compromised new version is then pulled in without review; pin versions and update deliberately.

Quick revision

  • Modern applications are mostly borrowed code (frameworks, libraries, their indirect dependencies), so security is largely the security of code you did not write. The category rose from 2021's "Vulnerable and Outdated Components" to 2025's broader "Software Supply Chain Failures" as attacks targeted this code and its pipelines.
  • Covers: vulnerable/outdated components, indirect (transitive) dependencies, compromised or malicious packages (including typosquatting), dependency confusion (public package shadows an internal name), and build/distribution pipeline compromise (malicious code in signed releases).
  • Defence, founded on inventory: software bill of materials (you cannot secure what you do not know you have), track and patch component vulnerabilities, verify integrity (signatures, checksums), reduce and vet dependencies, secure the pipeline (and prefer internal packages), and pin versions.

Test yourself

  1. Why did this category rise to prominence between the 2021 and 2025 OWASP editions?

Because modern applications consist largely of borrowed code, a small amount of the developers' own logic on a large foundation of third-party frameworks, libraries and their indirect dependencies, so an application's security is mostly the security of code it did not write. As attacks increasingly targeted this borrowed code and the pipelines that assemble it, exemplified by Log4Shell, OWASP broadened the 2021 "Vulnerable and Outdated Components" into the wider "Software Supply Chain Failures".

munotes.in405

Software Supply Chain Failures

  1. What is a transitive dependency, and why is it a particular risk?

A transitive, or indirect, dependency is a component that one of your chosen components depends on, which you did not select and may not know you are running. It is a particular risk because a vulnerability in it is your vulnerability, yet it is the one you are least likely to be aware of, which is why organisations struggled to answer whether they ran Log4j when it was buried several dependencies deep.

  1. What is a software bill of materials, and why is it the foundational control?

It is a machine-readable inventory of every component in an application, including indirect dependencies. It is foundational because you cannot secure, patch or assess a dependency you do not know you have, so when a widely-exploited component flaw appears, a bill of materials turns the question "do we run this?" from a multi-day investigation into an immediate query, enabling a response in hours rather than weeks.

  1. Distinguish a compromised component from a merely vulnerable one, and give an example of a supply-chain attack.

A vulnerable component contains an unintentional flaw that can be exploited, whereas a compromised component contains deliberately malicious code, either because an attacker published a malicious package or because a legitimate package was subverted at its source. An example is dependency confusion, where an attacker publishes a public package with the same name as an organisation's internal private package so that the build system fetches the malicious public one; pipeline compromise, injecting malicious code into signed releases, is also acceptable.

  1. Why is securing the build and distribution pipeline especially important?

Because the pipeline assembles and ships the software, so compromising it injects malicious code into legitimately-signed releases, which then reach every user through the trusted update channel with the authenticity of a genuine release. This is the most damaging form of supply-chain attack, since the malicious code bypasses the trust users place in signed updates, so the pipeline must be protected as a high-value target with access control, integrity verification and monitoring.

Contents This chapter on its own page

munotes.in406

Chapter Eighty-Seven

Injection: the Category and Its Members

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: Examine major web application vulnerabilities (OWASP Top 10), input validation flaws"

In one line

Injection is the single defect behind a whole family of attacks: untrusted input crossing into a place where it is interpreted as code or commands instead of treated as data. SQL injection, command injection and cross-site scripting are all this one flaw, in a database query, an operating-system command, and a web page respectively.

In examination wording: injection occurs when an application incorporates untrusted input into an interpreter, such as a database query, an operating-system command, or a web page, in a way that allows the input to change the intended structure or behaviour; its members share the mechanism of data being interpreted as code, and its defence is to keep input strictly as data in whatever context it is used.

The one idea

The value of treating injection as a category, before the individual chapters, is that the members are the same defect in different contexts, so understanding the idea once explains all of them.

The idea: an application takes some input and puts it into a place that interprets text, a database that interprets SQL, a shell that interprets commands, a browser that interprets HTML and script. If the input is placed into that interpreter such that it can become part of the instructions rather than remaining data, then crafted input changes what the interpreter does. The attacker's data has crossed the line into being the application's code.

Every injection attack is this line being crossed:

  • In SQL injection, input becomes part of a database query, so it can change the query.
  • In command injection, input becomes part of an operating-system command, so it can run commands.
  • In cross-site scripting, input becomes part of a web page, so it can run script in the victim's browser.
  • In LDAP injection, input becomes part of a directory query.
  • In template injection, input becomes part of a template the server evaluates.

The interpreter differs; the flaw is identical: the application failed to keep untrusted input as data, and the input became code.

Why it happens

Injection arises from building instructions by combining fixed text with input. A developer writes a query, a command or a page with a placeholder for a value, and fills the placeholder by inserting the input directly into the text. The interpreter then receives one combined string and cannot tell which part was the developer's instruction and which was the user's data; it interprets the whole thing, so input containing the interpreter's special characters or keywords is read as instructions.

This is the same root as directory traversal (building a path from input) and the same root the Log4Shell case showed (input evaluated as a lookup). It is the book's recurring failure: untrusted input placed where it will be interpreted.

munotes.in407

Injection: the Category and Its Members

The members

SQL injection. Input becomes part of a database query, allowing an attacker to read, modify or destroy data or bypass authentication. The most-studied member, with its own chapters (94 to 98) because MU names it separately and because it is both severe and definitively fixable.

Operating-system command injection. Input becomes part of a command the application runs on the server's operating system, allowing the attacker to run their own commands with the application's privileges, which can lead to full server compromise. It arises when an application builds a system command from input.

Cross-site scripting (XSS). Input becomes part of a web page, so the attacker's script runs in the victim's browser. Its own chapters (88, 89) because it is common and its defence has particular subtleties. Unlike the others, it targets the user rather than the server, which is why it is treated distinctly.

LDAP injection. Input becomes part of a directory query (the LDAP of the enumeration block), allowing unauthorised directory access.

Template injection. Input becomes part of a server-side template that the application evaluates, which can lead to code execution on the server.

Others: injection into XML processors, into mail headers, and into any other interpreter fed untrusted input.

The list is unified by the mechanism, and a student who meets a new interpreter can predict that feeding it untrusted input unsafely will produce an injection flaw of the same shape.

The shared defence

Because the members share a mechanism, they share a defence, stated here and detailed per member in the following chapters: keep untrusted input strictly as data in whatever context it is used, so it cannot become code.

The definitive form of this differs by interpreter but the principle is one:

  • For SQL, parameterised queries send the query structure and the data separately, so the data can never become part of the structure (chapter 97).
  • For OS commands, avoid building commands from input; use safe interfaces that pass arguments as data, not as a command string, and prefer application-level operations to shelling out at all.
  • For web pages, context-aware output encoding neutralises input for the exact place it is inserted, so it is displayed as data rather than run as script (chapter 89).
  • For every member, input validation (chapter 93) is a supporting layer: reject input that does not fit the expected shape, which reduces the surface but is not the primary fix, because attackers can craft valid-looking input that still injects.

The ordering matters and is the same for all: the primary fix is the context-specific separation of data from code (parameterisation, safe interfaces, output encoding); input validation supports it but does not replace it. A developer who relies on validation alone is filtering, which the traversal and Log4Shell cases showed is fragile.

munotes.in408

Injection: the Category and Its Members

A worked example, framed defensively

An assessor reviews an application for injection across its interpreters, using test inputs against a test account.

  • A search feature builds a database query from the search term. Injection-shaped input changes the query's behaviour. SQL injection. Fix: parameterised queries.
  • A file-conversion feature builds an operating-system command from a user-supplied filename. Input containing command separators runs additional commands. OS command injection, the most severe finding, since it can lead to server compromise. Fix: do not build the command from input; use a safe interface that passes the filename as an argument.
  • A comment field is displayed on a page without encoding, so input containing script runs in other users' browsers. Cross-site scripting. Fix: context-aware output encoding.
  • The assessor notes that all three are the same defect, untrusted input reaching an interpreter as code, and that each fix is the context-specific separation of data from code.

The report groups them as the injection family, which helps the client see the common cause and the common discipline (never let input become code) rather than three unrelated bugs, and the assessor demonstrates each with benign test input, not a destructive payload.

What beginners get wrong

  • Treating the members as unrelated attacks. SQL injection, command injection and cross-site scripting are the same defect, input interpreted as code, in different interpreters.
  • Missing the root cause. It is building instructions by combining fixed text with input, so the interpreter cannot separate code from data.
  • Thinking input validation is the fix. It is a supporting layer; the primary fix is context-specific separation of data from code, because attackers craft valid-looking input that still injects.
  • Underrating command injection. It runs commands with the application's privileges and can lead to full server compromise, often the most severe injection.
  • Not recognising XSS as injection. It is injection into a web page, distinguished only by targeting the user rather than the server.
  • Assuming a new interpreter is safe. Any interpreter fed untrusted input unsafely produces an injection flaw of the same shape.

Quick revision

  • Injection = untrusted input crossing into a place that interprets text (a database, a shell, a browser, a directory, a template) such that it becomes code or commands rather than data. One defect, many members.
  • Members: SQL injection (database query), OS command injection (system command; can compromise the server), cross-site scripting (web page; targets the user), LDAP injection (directory), template injection (server-side template; can execute code), and others.
  • Root cause: building instructions by combining fixed text with input, so the interpreter cannot tell code from data.
  • Shared defence: keep input strictly as data in its context so it cannot become code, by the context-specific separation (parameterised queries, safe command interfaces, context-aware output encoding); input validation supports but does not replace it.
munotes.in409

Injection: the Category and Its Members

Test yourself

  1. What is the single idea underlying all injection attacks?

That untrusted input is placed into an interpreter, such as a database, a shell, a browser or a directory, in a way that lets it become part of the instructions rather than remaining data, so crafted input changes what the interpreter does. The attacker's data crosses the line into being the application's code, and this one mechanism underlies SQL injection, command injection, cross-site scripting and the other members.

  1. Why does injection happen at the code level?

Because the application builds its instructions, a query, a command or a page, by combining fixed developer-written text with user input inserted directly into that text. The interpreter then receives one combined string and cannot distinguish the developer's instructions from the user's data, so input containing the interpreter's special characters or keywords is read as instructions rather than as data.

  1. Name four members of the injection family and the interpreter each targets.

SQL injection targets a database query; operating-system command injection targets a command run on the server's operating system; cross-site scripting targets a web page interpreted by the victim's browser; and LDAP injection targets a directory query. Template injection, targeting a server-side template, is also acceptable.

  1. Why is cross-site scripting treated as an injection attack, and how does it differ from the others?

Because it is injection of untrusted input into a web page, so the input becomes script that runs when the page is interpreted, which is the same data-becoming-code mechanism as the others. It differs in that it targets the user, running in the victim's browser, rather than the server, which is why it is treated in its own chapters despite sharing the injection mechanism.

  1. What is the shared defence for injection, and why is input validation not the primary fix?

The shared defence is to keep untrusted input strictly as data in whatever context it is used, so it cannot become code, achieved by context-specific separation of data from code: parameterised queries for SQL, safe interfaces that pass arguments as data for commands, and context-aware output encoding for web pages. Input validation is a supporting layer that reduces the surface but is not the primary fix, because attackers can craft input that passes validation yet still injects, so relying on validation alone is fragile filtering.

Contents This chapter on its own page

munotes.in410

Chapter Eighty-Eight

Cross-Site Scripting: Stored, Reflected and DOM-Based

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: Examine major web application vulnerabilities (OWASP Top 10), input validation flaws"

In one line

Cross-site scripting is injection into a web page: an attacker gets their script to run in a victim's browser in the trusted site's context, letting it steal the session token, act as the victim, or manipulate the page. It comes in three kinds by where the input is stored and how it reaches the page: stored, reflected, and DOM-based.

In examination wording: cross-site scripting is an injection vulnerability in which untrusted input is included in a web page without adequate neutralisation, causing the victim's browser to execute attacker-supplied script in the context of the trusted site; stored XSS persists the payload on the server, reflected XSS returns it in a response to a crafted request, and DOM-based XSS arises from client-side script handling input unsafely.

What XSS achieves

The injection chapter placed XSS in the family: input becomes part of a web page, so it runs as script. What makes it dangerous is where the script runs and with what trust.

The script runs in the victim's browser, in the context of the trusted site. That means it can do anything the site's own script could do on that page, on behalf of the victim, including:

  • Steal the session token, if it is accessible to script (the session block's third theft route), and send it to the attacker, taking over the victim's session.
  • Act as the victim: perform any action on the site that the victim could, by making requests as them from within the page.
  • Read data on the page: personal information, anything the victim can see.
  • Manipulate the page: alter what the victim sees, insert a fake login form to capture credentials, or redirect them.

The victim needs only to view a page containing the injected script; the attack runs automatically, silently. This is why XSS is severe: it turns the trusted site into a delivery mechanism for the attacker's code against the site's own users.

The contrast with CSRF, from the session block, is worth restating because it is the confusion students most need to resolve: XSS runs the attacker's script on the site (powerful: reads data, steals the token, acts as the user); CSRF makes the browser send a request to the site (narrower: causes an action, cannot read the response). XSS is the more powerful, which is why a site with XSS is in deeper trouble.

The three kinds

XSS is classified by how the malicious input reaches the page.

Stored (persistent) XSS. The attacker's input is saved on the server and later served to other users. The classic case: an attacker posts a comment, a profile field, or a message containing script; the application stores it without neutralising it; and every user who later views that content has the script run in their browser. This is the most dangerous kind, because it affects every viewer automatically, without any per-victim action, and it persists until removed. A stored XSS on a widely-viewed page can affect a great many users.

munotes.in411

Cross-Site Scripting: Stored, Reflected and DOM-Based

Reflected XSS. The attacker's input is returned immediately in the response to a request, not stored. The classic case: a search page that echoes the search term into the results page ("You searched for: X"); if the term is not neutralised, an attacker crafts a URL containing script as the search term, and a victim who follows that URL has the script run. Reflected XSS requires the victim to be lured to a crafted request (a link in a phishing message, say), so it is per-victim and needs delivery, but it is common because reflecting input into a page is common.

DOM-based XSS. The vulnerability is in the client-side script rather than the server. The page's own JavaScript takes input (from the URL, for instance) and inserts it into the page unsafely, so the input becomes script, without the server ever being involved in the injection. It is distinguished because the flaw and the fix are in the browser-side code, and it is easy to miss because a server-side review does not see it; the input never appears unsafely in the server's response, only in what the client-side script does with it.

KindWhere input goesWho is affectedNeeds
StoredSaved on the server, served laterEvery viewer, automaticallyNothing per-victim; persists
ReflectedReturned immediately in a responseThe victim of a crafted requestLuring the victim to the request
DOM-basedHandled unsafely by client-side scriptThe victim, via client-side handlingClient-side code flaw

Why XSS is so common

Two reasons a student should give:

  • Applications display user input constantly. Comments, names, search terms, messages, profile fields: any place user input is shown back is a potential XSS if the input is not neutralised for display. There are many such places, so missing one is easy.
  • Neutralising correctly is context-dependent and subtle. As the next chapter shows, the correct neutralisation depends on exactly where in the page the input is placed, and getting it wrong in one context leaves a hole. The subtlety is why frameworks that auto-encode have done more to reduce XSS than any single measure.

A worked example, framed defensively

An assessor tests an application for XSS, using benign marker inputs (not a real attack payload) to detect where input is reflected unsafely.

  • A comment field stores input and displays it to all viewers without neutralising it; a benign marker input appears in the page in a way that would execute if it were script. Stored XSS, the most serious, affecting every viewer. Fix: encode on output (next chapter).
  • A search page echoes the search term into the results without encoding; a crafted URL would run script for anyone who followed it. Reflected XSS. Fix: encode on output.
  • A page's client-side script reads a value from the URL and inserts it into the page using an unsafe method; the server never sees it unsafely. DOM-based XSS. Fix: the client-side code must insert the value safely (next chapter).
  • The assessor notes that a stored XSS on the comment page could steal the session token of every viewer whose session cookie is not HttpOnly, connecting to the session block, which is why HttpOnly and fixing the XSS are both needed.
munotes.in412

Cross-Site Scripting: Stored, Reflected and DOM-Based

The report classifies each by kind, explains that stored is worst because it affects every viewer automatically, and distinguishes XSS from CSRF for the client. The assessor uses harmless markers to locate the flaws, not a payload that acts on real users.

What beginners get wrong

  • Confusing XSS with CSRF. XSS runs the attacker's script on the site and can read data and steal the token; CSRF makes the browser send a request and cannot read the response. XSS is more powerful.
  • Thinking XSS only defaces pages. It can steal the session token, act as the victim, read their data, and capture credentials via a fake form; defacement is the least of it.
  • Underrating stored XSS. It affects every viewer automatically and persists, so it is the most dangerous kind; reflected needs luring, DOM-based needs a client-side flaw.
  • Missing DOM-based XSS in a server-side review. The flaw is in client-side script; the server never emits it unsafely, so it must be tested in the browser.
  • Believing HttpOnly alone fixes XSS. HttpOnly protects the token from theft; the XSS flaw can still act as the victim and read data, so the flaw itself must be fixed.
  • Assuming input validation stops XSS. It helps, but the primary fix is context-aware output encoding (next chapter), because valid-looking input can still contain script for some contexts.

Quick revision

  • XSS = injection into a web page; the attacker's script runs in the victim's browser in the trusted site's context, so it can steal the session token, act as the victim, read data, and manipulate the page. The victim need only view the page.
  • Against CSRF: XSS runs script on the site (powerful); CSRF sends a request to the site (narrower, cannot read the response).
  • Three kinds: stored (saved on the server, served to every viewer automatically, most dangerous, persists), reflected (returned immediately in a response, per-victim, needs luring), DOM-based (client-side script handles input unsafely; the flaw is in the browser code, missed by server-side review).
  • Common because applications display user input constantly and correct neutralisation is context-dependent and subtle.
munotes.in413

Cross-Site Scripting: Stored, Reflected and DOM-Based

Test yourself

  1. What does cross-site scripting achieve, and why is where the script runs significant?

It causes the attacker's script to run in the victim's browser in the context of the trusted site, so the script can do anything the site's own script could on behalf of the victim: steal the session token if it is script-accessible, act as the victim by making requests as them, read data on the page, and manipulate what the victim sees, including inserting a fake login form. Running in the trusted site's context with the site's privileges is what makes it powerful, and the victim needs only to view the page.

  1. Distinguish stored, reflected and DOM-based XSS.

Stored XSS saves the attacker's input on the server and serves it to other users later, so it affects every viewer automatically and persists; reflected XSS returns the input immediately in the response to a crafted request, so it affects the victim of that request and requires luring them to it; DOM-based XSS arises from the page's own client-side script handling input unsafely, so the flaw and fix are in the browser code and the server never emits the input unsafely.

  1. Why is stored XSS the most dangerous of the three kinds?

Because the payload is saved on the server and served to every user who views the affected content, so it affects all viewers automatically without any per-victim action and persists until removed. Reflected XSS requires luring each victim to a crafted request, and DOM-based XSS depends on a client-side flaw, whereas stored XSS on a widely-viewed page can compromise many users passively.

  1. How does XSS differ from CSRF?

XSS runs the attacker's script on the trusted site in the victim's browser, giving full capability on the page including reading the response, stealing the session token and acting as the victim, and it requires an XSS flaw. CSRF makes the victim's browser send a request to the site and cannot read the response, so it only causes state-changing actions, and it needs no flaw in the target beyond the target authenticating on the cookie alone. XSS is the more powerful.

  1. Why is DOM-based XSS easy to miss, and where must it be fixed?

Because the vulnerability is in the client-side script rather than the server: the server's response does not contain the input unsafely, so a server-side review does not see it, and the injection happens only when the page's own JavaScript inserts input into the page unsafely. It must therefore be tested in the browser and fixed in the client-side code, by having that code insert values safely rather than in ways that let them become script.

Contents This chapter on its own page

munotes.in414

Chapter Eighty-Nine

Cross-Site Scripting Defences: Output Encoding and Content Security Policy

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: ... input validation flaws"

In one line

The real fix for cross-site scripting is context-aware output encoding: neutralising input for the exact place it is inserted in the page, so it is displayed as data and never runs as script. Framework auto-escaping delivers this in practice, HttpOnly protects the token, and Content-Security-Policy is defence in depth.

In examination wording: cross-site scripting is prevented primarily by encoding untrusted data appropriately for the context in which it is output, so that it cannot be interpreted as script; this is delivered by framework auto-escaping, supported by input validation, and complemented by the HttpOnly cookie flag limiting token theft and Content-Security-Policy restricting which scripts the browser will execute.

The real fix: output encoding

The injection chapter gave the shared defence: keep input as data in its context so it cannot become code. For XSS, "its context" is a web page, and the neutralisation is output encoding (also called output escaping).

Output encoding converts characters that have special meaning in the page into a form that displays as those characters rather than being interpreted. The characters that let input become script, the ones that open and close tags and script, are replaced with representations that the browser shows as text and does not act on. So an input containing what would be a script becomes, on the page, the literal text of that script, displayed and inert, rather than something the browser runs.

The crucial word is output: the encoding happens when the data is written into the page, not when it is received. This matters for two reasons:

  • The same data may be shown in several places, each needing its own encoding; encoding on output handles each correctly.
  • Stored XSS is caught because the encoding happens every time the stored data is displayed, so even data saved unsafely is rendered safely.

Encoding on output, rather than trying to clean input on the way in, is the principle, and it is why "output encoding" is the precise name.

The central subtlety: context

Here is the examinable point students most often miss: the correct encoding depends on where in the page the input is placed. A web page has several distinct contexts, and each interprets characters differently, so each needs a different encoding.

The main contexts:

  • Inside the body of the page (between tags), where the input becomes text.
  • Inside an attribute of a tag, where different characters are dangerous.
  • Inside a script block, where the input is in a different language.
  • Inside a URL, where URL encoding applies.
  • Inside a style, another context again.

Encoding correctly for one context but placing the input in another leaves a hole: input encoded for the page body but inserted into an attribute or a script may still break out and execute, because the dangerous characters differ. So the rule is: encode for the specific context where the data is output, and know which context that is. This is why XSS defence is subtle and why doing it by hand is error-prone.

munotes.in415

Cross-Site Scripting Defences: Output Encoding and Content Security Policy

How it is done in practice: framework auto-escaping

Because context-aware encoding by hand is error-prone, the practical answer is frameworks that encode automatically. Modern web frameworks, when data is placed into a page through their templating, automatically apply the correct encoding for the context, so the developer does not have to remember to encode each value or to choose the right encoding. This has done more to reduce XSS than any other single measure, because it makes the safe path the default path.

Two consequences a student should know:

  • Use the framework's safe output mechanisms, and do not bypass them. Frameworks provide a way to output raw, unencoded content for the rare case where it is genuinely needed; using that with untrusted input reintroduces XSS. The common cause of XSS in a framework-using application is a developer bypassing the auto-escaping.
  • DOM-based XSS needs care in client-side code, because the framework's server-side escaping does not cover what client-side script does with input. The client-side code must insert input using safe methods (that treat it as text) rather than unsafe ones (that interpret it as markup).

The supporting and defence-in-depth measures

Input validation. As with all injection, validating input (rejecting input that does not fit the expected shape) reduces the surface but is not the primary fix, because valid-looking input can still contain script for some contexts, and because the same input may be safe in one context and dangerous in another. Validate on input, encode on output, and rely on the encoding.

The HttpOnly cookie flag. From the session block: it makes the session cookie invisible to script, so even if an XSS flaw exists, it cannot steal the session token through the cookie. This does not fix the XSS (the script can still act as the victim and read data), but it protects the token specifically, which is why it is part of the layered defence.

Content-Security-Policy (CSP). From the hardening chapter, the defence-in-depth measure. CSP tells the browser which sources of script it may execute; a strong policy allowing scripts only from trusted sources means that even if an attacker injects a script, the browser refuses to run it because it is not from an allowed source. CSP does not fix the underlying XSS flaw, but it can neutralise its impact, catching what output encoding missed. It is valuable precisely because output encoding, being subtle, is sometimes wrong, and CSP is the net beneath it.

munotes.in416

Cross-Site Scripting Defences: Output Encoding and Content Security Policy

The layered defence

The order and role of each measure:

  1. Context-aware output encoding, delivered by framework auto-escaping: the real fix, neutralising input for the exact context so it cannot become script.
  2. Safe client-side coding for DOM-based XSS, inserting input as text not markup.
  3. Input validation: a supporting layer, reducing surface.
  4. HttpOnly on the session cookie: protects the token even if XSS occurs.
  5. Content-Security-Policy: defence in depth, so the browser refuses injected scripts even where encoding failed.

A site with all of these has the flaw fixed at the source and its impact limited if the fix is imperfect, which is the layered posture the block recommends throughout.

A worked example, framed defensively

An assessor reviews an application's XSS defences after finding the flaws of the previous chapter.

  • The comment field (stored XSS) is displayed without encoding. Fix: encode on output for the page-body context, via the framework's safe templating. Verified: a benign marker input now displays as inert text.
  • A value is inserted into an HTML attribute with body-context encoding, which is the wrong context. Finding: encoding mismatch, still exploitable. Fix: use attribute-context encoding (or the framework's context-aware output).
  • The application in one place bypasses the framework's auto-escaping to output raw content, with untrusted input. Finding: the safe default was bypassed. Fix: use the safe output; encode.
  • The session cookie is not HttpOnly, and there is no CSP. Fixes: set HttpOnly (protect the token) and add a Content-Security-Policy (defence in depth).

The report presents the layered defence, stressing that the primary fix is context-aware output encoding delivered by the framework, that the encoding-mismatch finding shows why context matters, and that HttpOnly and CSP limit the impact if any encoding is missed. The assessor verifies each fix with benign markers.

What beginners get wrong

  • Encoding on input instead of output. The neutralisation happens when data is written into the page, in the correct context; encoding on input misses contexts and does not catch stored data rendered elsewhere.
  • Using one encoding everywhere. The correct encoding depends on the context (body, attribute, script, URL, style); the wrong context leaves a hole.
  • Relying on input validation. It supports the fix but does not replace it; valid-looking input can still be script for some contexts.
  • Bypassing framework auto-escaping. The common cause of XSS in a framework application; use the safe output mechanisms and do not output raw untrusted content.
  • Ignoring DOM-based XSS. Server-side escaping does not cover client-side handling; the client code must insert input as text.
  • Thinking HttpOnly or CSP fixes XSS. They limit impact (token theft; running injected scripts) but do not fix the flaw; encode on output, and use them as defence in depth.
munotes.in417

Cross-Site Scripting Defences: Output Encoding and Content Security Policy

Quick revision

  • The real fix: context-aware output encoding, neutralising input for the exact place it is written into the page, on output, so it displays as data and cannot run as script. Catches stored XSS because it encodes every time the data is displayed.
  • The subtlety: the correct encoding depends on the context (page body, attribute, script, URL, style); the wrong context leaves a hole.
  • Delivered in practice by framework auto-escaping (the safe default); the common failure is bypassing it to output raw untrusted content. DOM-based XSS needs safe client-side coding (insert as text, not markup).
  • Layered: encoding (the fix), input validation (support), HttpOnly (protect the token), Content-Security-Policy (defence in depth: the browser refuses injected scripts).

Test yourself

  1. What is the primary defence against cross-site scripting, and why is it done on output rather than input?

Context-aware output encoding, which converts characters that have special meaning in the page into a form that displays as those characters rather than being interpreted, so untrusted input is shown as inert data and never runs as script. It is done on output, when the data is written into the page, because the same data may be shown in several contexts each needing its own encoding, and because encoding on output catches stored data safely every time it is displayed, whereas cleaning on input misses contexts and stored cases.

  1. Why is the context in which input is placed critical to encoding it correctly?

Because a web page has several distinct contexts, the page body, tag attributes, script blocks, URLs and styles, and each interprets characters differently, so each requires a different encoding. Encoding correctly for one context but placing the input in another leaves a hole, since input encoded for the page body may still break out and execute when inserted into an attribute or a script, where the dangerous characters differ.

  1. How is context-aware encoding achieved in practice, and what is the common cause of XSS in framework-using applications?

By using web frameworks that automatically apply the correct encoding for the context when data is placed into a page through their templating, making the safe path the default. The common cause of XSS in such applications is a developer bypassing the auto-escaping, for example using the framework's mechanism for outputting raw, unencoded content with untrusted input, which reintroduces the flaw.

  1. What does the HttpOnly flag contribute to XSS defence, and what does it not do?

It makes the session cookie invisible to client-side script, so even if an XSS flaw exists, the injected script cannot steal the session token through the cookie. It does not fix the XSS flaw itself, which can still act as the victim by making requests as them and read data on the page, so the flaw must still be fixed by output encoding; HttpOnly protects the token specifically as part of the layered defence.

munotes.in418

Cross-Site Scripting Defences: Output Encoding and Content Security Policy

  1. How does Content-Security-Policy provide defence in depth against XSS?

It tells the browser which sources of script it is permitted to execute, so a strong policy allowing scripts only from trusted sources means that even if an attacker injects a script into the page, the browser refuses to run it because it is not from an allowed source. It does not fix the underlying flaw but neutralises its impact, acting as a net beneath output encoding for cases where the encoding was subtly wrong.

Contents This chapter on its own page

munotes.in419

Chapter Ninety

Insecure Design and Authentication Failures

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: Examine major web application vulnerabilities (OWASP Top 10)"

In one line

Insecure Design is a flaw in the application's design, present before any code is written, which careful coding cannot fix because the plan itself is unsafe. Authentication Failures is weak handling of login, credentials and sessions, which the password and session blocks already covered.

In examination wording: Insecure Design is the OWASP category recognising that some vulnerabilities arise from missing or flawed security design rather than implementation defects, requiring threat modelling and secure design practices; Authentication Failures (formerly Identification and Authentication Failures) covers weaknesses in confirming identity and managing sessions, addressed by the authentication and session controls established earlier.

Insecure Design: the flaw in the plan

This is the more novel of the two, added as its own category to make a point the rest of the Top 10 does not: not every vulnerability is a coding mistake. Some are in the design.

The distinction is important and examinable. An implementation flaw is code that does the wrong thing: a query built by concatenation (injection), a missing authorisation check (broken access control), a value not encoded (XSS). You fix it by correcting the code. An insecure design flaw is different: the code may be written perfectly, doing exactly what it was designed to do, and the design itself is unsafe. No amount of careful coding fixes it, because the plan is the problem.

Examples make the distinction concrete:

  • A password-reset flow designed to verify identity only by a security question whose answer is publicly discoverable. The code implementing it may be flawless; the design is insecure, because the identity check is inadequate by design.
  • A funds-transfer feature designed without any limit or second check on large transfers. Implemented correctly, it still allows a single request to move any amount, because the design omitted the control.
  • A workflow designed so that a step can be skipped, allowing a user to reach a later state (say, a completed order) without the earlier required steps (say, payment). The code faithfully implements the flawed workflow.
  • A system designed to trust a value from the client that should be authoritative on the server (the cookie-manipulation shape, at the design level).

In each case, testing the implementation for bugs finds nothing, because there is no bug; the flaw is that the design did not include a control it needed, or included an unsafe one.

The defence is design-time, not code-time:

  • Threat modelling: during design, systematically ask what could go wrong, who might attack the feature, and what controls it needs, so that security controls are part of the design rather than added later. This is the primary practice, and its absence is the root of insecure design.
  • Secure design patterns: reusing designs known to be safe (a proper password-reset flow, a workflow that cannot be skipped, limits and second checks on sensitive actions).
  • Considering abuse cases, not only use cases: designing for how the feature could be misused, not only how it is meant to be used.
  • Security requirements: stating the security properties a feature must have as requirements, so they are designed in.
munotes.in420

Insecure Design and Authentication Failures

The category exists to make the point that you cannot test or code your way out of an insecure design; security must be designed in from the start, which is the "shift left" idea the vulnerability-lifecycle chapter mentioned: the cheapest and most effective place to address security is before the code is written.

Authentication Failures

The familiar category, formerly "Identification and Authentication Failures", covering weaknesses in confirming who a user is and managing their session. The book has treated this thoroughly, so this section places it in the frame and points back, as the misconfiguration-and-cryptography chapter did.

What it covers:

  • Weak passwords and password policy: permitting weak or breached passwords, the password chapters' subject.
  • Credential-stuffing susceptibility: allowing unlimited login attempts and not detecting reuse of breached credentials.
  • Weak or absent multi-factor authentication: the password-policy chapter's subject.
  • Session management flaws: the whole session block, weak tokens, no HTTPS, no HttpOnly, fixation, poor expiry.
  • Weak credential recovery: an insecure password-reset flow (which shades into Insecure Design).
  • Exposed or weakly-stored credentials: the storage-model failures of the cryptography block.

Where its full treatment is: the password block (chapters 56 to 60) for credentials and storage, the password-policy chapter (59) for policy and multi-factor, and the entire session block (72 to 77) for session management. Everything there is this OWASP category.

The fix, assembled from those blocks: strong password policy with breach screening, multi-factor authentication, correct password storage (slow salted hash), rate limiting and lockout against guessing, the full session-defence checklist, and a secure credential-recovery design. There is nothing new here; the category is a heading under which the book's authentication and session material is filed.

Why pair these two

The pairing teaches a useful contrast: Insecure Design is a category of failures that precede code, requiring a design-time response, while Authentication Failures is a category the book already covered in implementation detail. Together they show the two ends of the spectrum: some Top-10 categories point to disciplines not yet named (threat modelling, secure design), and others gather material already taught. A student who sees both understands that securing an application spans from the design, before any code, to the implementation of well-understood controls.

A worked example, framed defensively

An assessor reviews an application against both categories.

  • The password-reset flow verifies identity by a security question with a publicly-discoverable answer. Insecure Design: the identity check is inadequate by design, and the code implementing it is not at fault. Fix: redesign the flow (a link to a verified email, multi-factor). Recommendation: introduce threat modelling so such design flaws are caught before coding.
  • A large-transfer feature has no limit or second check. Insecure Design: a control the design omitted. Fix: design in limits and a second authoriser.
  • Login permits unlimited attempts and does not screen breached passwords. Authentication Failures. Fix: rate limiting, lockout, breach screening (password-policy chapter).
  • Session tokens lack HttpOnly and are not regenerated at login. Authentication Failures (session management). Fix: the session-defence checklist.
munotes.in421

Insecure Design and Authentication Failures

The report distinguishes the two design findings, which no code review would catch, from the authentication findings, which are implementation gaps in well-understood controls, and recommends threat modelling as the practice that would have caught the design flaws. The assessor establishes the design flaws by reasoning about the feature's logic, and the authentication flaws by testing, both within a test account.

What beginners get wrong

  • Thinking every vulnerability is a coding bug. Insecure Design flaws are in the plan; the code may be perfect, and no coding or testing fixes an unsafe design.
  • Trying to test or code away an insecure design. The fix is design-time: threat modelling, secure design patterns, abuse cases, security requirements.
  • Confusing Insecure Design with implementation flaws. An implementation flaw is code doing the wrong thing; an insecure design is code correctly implementing an unsafe plan.
  • Treating Authentication Failures as new. It is the password and session blocks; place it in the frame and apply that material.
  • Designing a password-reset around a discoverable secret. A classic insecure design; use a verified channel and multi-factor.
  • Considering only use cases. Secure design considers abuse cases: how the feature could be misused, not only how it is meant to be used.

Quick revision

  • Insecure Design: the flaw is in the design, present before coding, which careful implementation cannot fix because the plan is unsafe (inadequate reset checks, missing limits, skippable workflows). Fix at design time: threat modelling (the primary practice), secure design patterns, abuse cases, security requirements. You cannot code or test your way out of an insecure design.
  • Authentication Failures (formerly Identification and Authentication Failures): weak login, credential and session handling. Full treatment in the password block (56 to 60), password-policy chapter (59), and session block (72 to 77). Fix: strong policy with breach screening, multi-factor, correct storage, rate limiting and lockout, the session-defence checklist, secure recovery.
  • The pairing spans the spectrum: some categories precede code (design), others were covered as implementation.

Test yourself

  1. What distinguishes an insecure design flaw from an implementation flaw?
munotes.in422

Insecure Design and Authentication Failures

An implementation flaw is code that does the wrong thing, such as an injection or a missing authorisation check, and is fixed by correcting the code. An insecure design flaw is code that correctly implements an unsafe plan: the design itself lacks a needed control or includes an inadequate one, so the code may be flawless and the vulnerability remains, and no amount of careful coding or testing fixes it because the problem is the design.

  1. Give an example of an insecure design and explain why testing the code would not find it.

A password-reset flow designed to verify identity only by a security question whose answer is publicly discoverable. Testing the code finds no bug, because the code faithfully implements the flow as designed; the flaw is that the design chose an inadequate identity check, so the weakness lies in the plan rather than in any implementation defect that a code review or functional test would detect.

  1. What is the primary defence against insecure design, and why is it a design-time practice?

Threat modelling: during design, systematically identifying what could go wrong, who might attack the feature and what controls it needs, so that security controls are designed in rather than added afterwards. It is a design-time practice because an insecure design cannot be corrected by coding or testing; the missing or inadequate control must be built into the design before implementation, which is the cheapest and most effective point to address it.

  1. Why is the Authentication Failures category treated briefly in this chapter?

Because the book has already covered it thoroughly: credentials and their storage in the password and cryptography blocks, password policy and multi-factor authentication in the password-policy chapter, and session management in the entire session block. It is therefore placed in the OWASP frame and referred back to that material, since it gathers already-taught implementation controls rather than introducing new ones.

  1. What does the pairing of these two categories illustrate about securing an application?

That securing an application spans a spectrum: some Top-10 categories, like Insecure Design, point to failures that precede code and require design-time disciplines such as threat modelling, while others, like Authentication Failures, gather well-understood implementation controls covered earlier. Together they show that security must be considered both in the design, before any code is written, and in the correct implementation of established controls.

Contents This chapter on its own page

munotes.in423

Chapter Ninety-One

Integrity, Logging and Exceptional Conditions

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: Examine major web application vulnerabilities (OWASP Top 10)"

In one line

Three Top-10 categories, each a different omission: Software or Data Integrity Failures (trusting code or data whose integrity was never checked), Security Logging and Alerting Failures (breaches unseen because nothing is logged or watched), and Mishandling of Exceptional Conditions (errors and edge cases handled unsafely).

In examination wording: Software or Data Integrity Failures cover reliance on code or data without verifying its integrity, including insecure deserialisation and unverified updates; Security Logging and Alerting Failures cover inadequate recording and monitoring that allow breaches to go undetected; Mishandling of Exceptional Conditions, introduced in 2025, covers unsafe handling of errors and unexpected states.

Software or Data Integrity Failures

The idea. This category is about trusting code or data whose integrity has not been verified, so that an attacker who can alter that code or data compromises the application. It connects to the supply-chain category (integrity of components) and to the integrity leg of the CIA triad.

The forms:

  • Unverified updates. An application that accepts software updates without verifying they are genuine (signed by the real vendor) can be given a malicious update by an attacker who intercepts or substitutes it. The update mechanism must verify integrity, or it becomes a way in, which is the pipeline-compromise idea from the supply-chain chapter at the application level.
  • Insecure deserialisation. When an application takes serialised data (a structured object encoded for transport or storage) from an untrusted source and reconstructs it without verifying its integrity, a crafted serialised object can cause unexpected and dangerous behaviour, in the worst case code execution. This is a specific, well-known member and worth recognising by name: untrusted serialised data reconstructed without verification.
  • Trusting data whose integrity is not checked. Relying on data from an untrusted source, or that could have been altered in transit or storage, without a check (a signature, a hash) that it is unchanged.

The defence: verify integrity before trusting. Verify signatures on updates and on code; do not deserialise untrusted data, or do so only with integrity checks and strict limits on what may be reconstructed; sign or otherwise protect data whose integrity matters; and, at the component level, the supply-chain chapter's verification of dependencies.

Security Logging and Alerting Failures

The idea. This category is about not being able to see attacks, because the application does not log the events that matter, or logs them and nobody watches. It is the application-level counterpart of the detection material from Module 1, and it is a Top-10 category because inadequate logging is what lets breaches go undetected for long periods.

The forms:

  • Not logging security-relevant events: logins and failures, access-control failures, high-value actions, input-validation failures. If these are not recorded, an attack leaves no trace to find, exactly as the covering-tracks chapter warned about system logs.
  • Logging without monitoring: recording events but not watching them, so alerts never fire and logs are read only after a breach is discovered by other means.
  • Logs that can be tampered with, or that are kept only locally, the covering-tracks chapter's concern applied to application logs: they should be protected and ideally sent off-host.
  • Logging sensitive data: the opposite failure, recording passwords, tokens or personal data in logs, which turns the logs into a target, the reader-stamp and confidentiality concern.
munotes.in424

Integrity, Logging and Exceptional Conditions

The defence: log the security-relevant events, protect the logs, monitor and alert on them, and do not log sensitive data. This is the covering-tracks and detection material of Module 1 applied to the application: an application should record what matters, in a form that supports detection and investigation, without itself becoming a disclosure risk. Because most real breaches are detected late or by third parties, improving logging and monitoring shortens the time to detection, which is the whole value.

Mishandling of Exceptional Conditions

The idea. New in the 2025 edition, this category recognises that how an application handles errors, failures and unexpected states is a security matter. An application that handles the normal path correctly but mishandles the exceptional path can be attacked through the exception.

The forms:

  • Failing open: when a check fails or a component is unavailable, proceeding as though it succeeded rather than denying. The access-control chapter's "deny by default" is this principle: an authorisation check that fails open grants access. A security control that fails open is worse than none, because it gives false assurance.
  • Verbose errors: disclosing internal detail in error messages, the web-server block's finding, seen here as an exceptional-condition failure.
  • Inconsistent behaviour on error: error paths that skip validation, release resources incorrectly, or leave the application in an insecure state.
  • Unhandled edge cases: inputs or states the design did not anticipate, handled in undefined and possibly unsafe ways, which shades into insecure design.

The defence: handle exceptional conditions safely and deliberately. Fail closed, so a failed check denies rather than grants; return generic errors to users while logging detail server-side; ensure error paths maintain the application's security properties; and design for the exceptional cases, not only the normal ones (the abuse-case thinking of the insecure-design chapter). The principle: the exceptional path deserves the same security attention as the normal path, because attackers deliberately trigger the exceptional path.

Why group these three

They are grouped because each is a category of omission rather than a specific attack: failing to verify integrity, failing to log and watch, failing to handle the exceptional safely. None is a single technique like injection; each is a discipline the application must have. Grouping them keeps the OWASP block complete without giving a full chapter to categories that are largely applications of principles already established (integrity from the CIA and supply-chain material, logging from the detection material, safe failure from access control's deny-by-default). A student should be able to name each, give its idea and one form, and its defence.

munotes.in425

Integrity, Logging and Exceptional Conditions

A worked example, framed defensively

An assessor reviews an application against these three categories.

  • The application accepts updates without verifying signatures. Integrity Failure. Fix: verify update signatures.
  • It deserialises data from an untrusted source without integrity checks. Integrity Failure (insecure deserialisation). Fix: do not deserialise untrusted data, or verify integrity and limit reconstruction.
  • Access-control failures and login failures are not logged, and no monitoring exists. Logging and Alerting Failure. Fix: log security-relevant events, protect the logs off-host, and monitor.
  • An authorisation check fails open when a dependency is unavailable, granting access. Mishandling of Exceptional Conditions. Fix: fail closed.
  • Verbose errors disclose internal detail. Mishandling of Exceptional Conditions / Misconfiguration. Fix: generic errors, detail to logs.

The report notes that these are disciplines the application lacks rather than single bugs, and that each maps to a principle already established, which reassures the client that the fixes are well understood. The assessor establishes them by reviewing behaviour and configuration.

What beginners get wrong

  • Thinking integrity failures are only about the supply chain. They include unverified updates and insecure deserialisation within the application: trusting code or data whose integrity was not checked.
  • Not recognising insecure deserialisation. Reconstructing untrusted serialised data without verification is a specific, dangerous integrity failure that can lead to code execution.
  • Treating logging as an operations detail, not a security control. Inadequate logging and monitoring is why breaches go undetected; log the right events, protect and watch them.
  • Logging sensitive data. It turns the logs into a target; log what matters without recording passwords, tokens or personal data.
  • Ignoring the exceptional path. Attackers trigger errors and edge cases deliberately; a control that fails open, or an error that leaves the app insecure, is exploited. Fail closed.
  • Failing open. A security control that proceeds when its check fails gives false assurance and is worse than none.

Quick revision

  • Software or Data Integrity Failures: trusting code or data whose integrity is unverified. Forms: unverified updates, insecure deserialisation (reconstructing untrusted serialised data), trusting unchecked data. Fix: verify integrity before trusting (signatures, no deserialising untrusted data).
  • Security Logging and Alerting Failures: breaches unseen because events are not logged, or logged and not watched. Forms: not logging security events, no monitoring, tamperable or local-only logs, or logging sensitive data. Fix: log the right events, protect the logs, monitor and alert, do not log secrets (Module 1's detection material at the application).
  • Mishandling of Exceptional Conditions (new 2025): errors and edge cases handled unsafely. Forms: failing open, verbose errors, insecure error paths, unhandled edge cases. Fix: fail closed, generic errors with detail logged, secure error paths, design for abuse cases. The exceptional path deserves the same attention as the normal path.
  • Grouped as categories of omission, each applying an established principle.
munotes.in426

Integrity, Logging and Exceptional Conditions

Test yourself

  1. What does the Software or Data Integrity Failures category cover, and what is insecure deserialisation?

It covers reliance on code or data whose integrity has not been verified, so that an attacker who can alter it compromises the application, including accepting software updates without verifying they are genuinely from the vendor. Insecure deserialisation is a specific member: taking serialised data from an untrusted source and reconstructing it into an object without verifying its integrity, so that a crafted serialised object can cause dangerous behaviour, in the worst case code execution.

  1. Why is inadequate logging and monitoring a Top-10 category rather than an operational detail?

Because it is what allows breaches to go undetected, often for long periods and frequently discovered only by third parties. If an application does not log security-relevant events, an attack leaves no trace to find, and if it logs but nobody monitors, alerts never fire; improving logging and monitoring directly shortens the time to detection, which determines how much damage an attack does, so it is a security control in its own right.

  1. What should and should not be logged, and how should logs be protected?

Security-relevant events should be logged: logins and failures, access-control failures, high-value actions and input-validation failures; sensitive data such as passwords, tokens and personal information should not be logged, since that turns the logs into a target. The logs should be protected against tampering and ideally sent off-host to a separate collector, so they remain trustworthy after a compromise, and they should be monitored so that attacks are detected.

  1. What does "failing open" mean, and why is it a security failure?

Failing open means that when a check fails or a component is unavailable, the application proceeds as though the check had succeeded rather than denying the action. It is a security failure because a control that grants access when its check cannot be performed gives false assurance and is worse than having no control, so security checks should fail closed, denying by default, which is the deny-by-default principle applied to exceptional conditions.

  1. Why are these three categories grouped, and what do they have in common?

They are grouped because each is a category of omission rather than a specific attack technique: failing to verify integrity before trusting code or data, failing to log and monitor so attacks are seen, and failing to handle errors and edge cases safely. Each is a discipline the application must have rather than a single bug, and each applies a principle already established elsewhere in the book, integrity, detection, and deny-by-default, to the application layer.

Contents This chapter on its own page

munotes.in427

Chapter Ninety-Two

Server-Side Request Forgery

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: Examine major web application vulnerabilities (OWASP Top 10)"

In one line

Server-side request forgery makes the server fetch a URL the attacker chose, so the attacker reaches systems the server can reach but they cannot, especially internal services. It was its own OWASP category in 2021 and is folded into Broken Access Control in 2025, because it is fundamentally a request reaching somewhere it should not.

In examination wording: server-side request forgery is an attack in which an application is induced to make a request to a URL supplied or influenced by the attacker, causing the server to access resources on the attacker's behalf, including internal services unreachable from outside; it is prevented by validating and restricting the destinations the server may request and by network controls limiting what the server can reach.

The mechanism

Many applications legitimately make requests to other URLs on the server side: fetching an image from a URL a user supplies, calling an external service, retrieving a document, checking a link. The feature is common and useful.

The vulnerability arises when the application lets the user influence the destination of that server-side request without adequate restriction. The attacker supplies a URL, and the server fetches it, on the attacker's behalf, from the server's own network position.

Why this is powerful, and it is the key point: the server can reach things the attacker cannot. The server sits inside the organisation's network, behind the firewall, so it can reach:

  • Internal services not exposed to the internet: internal APIs, databases, administrative interfaces, other servers.
  • The server's own local services, reachable only from the machine itself.
  • Cloud metadata services, a particularly important case: cloud platforms expose, to a server, a special internal address that returns the server's configuration and often its credentials. An SSRF that reaches this address can retrieve the server's cloud credentials, which is a severe escalation, and it is why SSRF became prominent as applications moved to the cloud.

So the attacker uses the server as a proxy to reach internal systems, turning the application's ability to make requests into the attacker's ability to reach the internal network. They ask the server "fetch this internal address for me", and the server, being on the inside, does.

What the attacker gains, and the limit

  • Reaching internal systems: probing and accessing internal services from the server's position, mapping the internal network, and reaching administrative interfaces.
  • Retrieving cloud credentials: via the metadata service, potentially the most severe outcome.
  • Reading internal responses, where the application returns the fetched content to the attacker (this is "in-band" SSRF).

A limit, sometimes: in blind SSRF, the application makes the request but does not return the response to the attacker, so the attacker can cause the request (and its side effects) but cannot directly read what comes back, inferring results indirectly. This is analogous to blind SQL injection, and it is less powerful but still dangerous, since causing an internal request can itself have effects.

munotes.in428

Server-Side Request Forgery

Why it is folded into Broken Access Control in 2025

The OWASP overview chapter noted this reclassification, and understanding it is a good test of understanding the attack. SSRF is, at bottom, a request reaching a resource it should not be allowed to reach: the server accesses an internal service that the request should not have been authorised to reach. That is an access-control failure, the request crosses a boundary it should not, so grouping it under Broken Access Control in 2025 reflects that SSRF is fundamentally about a request reaching an unauthorised destination.

The reclassification does not change the attack or its defences; it changes the heading, and it teaches that categories are ways of organising, not fixed truths, which the overview chapter emphasised.

The defences

The fixes restrict where the server may make requests and limit what it can reach:

Validate and restrict the destination. Do not let the user freely specify the URL the server fetches. Where the server must fetch a user-influenced URL:

  • Use an allow-list of permitted destinations (specific domains or addresses the feature legitimately needs), rejecting anything else. This is the strongest fix, mirroring the directory-traversal chapter's allow-list approach: constrain to known-good rather than trying to block known-bad.
  • Block internal and reserved addresses: reject requests to internal address ranges, the local machine, and the cloud metadata address. This is a deny-list and is weaker than an allow-list (attackers find encodings and redirects to reach blocked addresses, the recurring filtering-is-fragile lesson), so it supplements rather than replaces the allow-list.
  • Do not follow redirects to unauthorised destinations, since a redirect can send an allow-listed request onward to a blocked one.

Network controls. Limit what the server can reach, so that even a successful SSRF reaches little:

  • Segment the network so the application server cannot reach sensitive internal services it does not need (least privilege for network reach), which is the segmentation principle applied.
  • Protect the cloud metadata service: cloud platforms provide hardened versions of the metadata service that resist SSRF, and these should be used; restrict the server's access to it.
  • Egress filtering from the server, so it cannot make arbitrary outbound requests, connecting to the amplification and Log4Shell chapters' egress point.

The combination: allow-list the destinations, block internal and metadata addresses as a supplement, do not follow redirects, and use network segmentation and egress controls so a successful SSRF reaches little. The primary fix is constraining the destination; the network controls are defence in depth.

munotes.in429

Server-Side Request Forgery

A worked example, framed defensively

An assessor tests an application feature that fetches a user-supplied URL (an "import from URL" function), using benign internal test addresses.

  • Supplying an internal address causes the server to fetch it and return the response, revealing an internal service not exposed to the internet. SSRF (in-band): the server is used as a proxy to reach the internal network. Fix: allow-list permitted destinations; block internal addresses.
  • Supplying the cloud metadata address returns the server's cloud credentials. The most severe finding: SSRF to the metadata service. Fix: use the hardened metadata service, restrict access, and allow-list destinations.
  • The feature follows redirects, so an allow-listed URL redirecting to an internal one is fetched. Finding: redirect bypass. Fix: do not follow redirects to unauthorised destinations.
  • The application server can reach broad internal ranges. Finding: no segmentation, so a successful SSRF reaches much. Fix: segment and apply egress filtering.

The report explains that SSRF turns the server into a proxy for the attacker to reach the internal network, that the cloud-metadata case is the severe one, and that it is now classified under Broken Access Control because it is a request reaching an unauthorised destination. The assessor uses benign internal test targets to demonstrate the flaw, not to access real internal systems beyond what proves it.

What beginners get wrong

  • Thinking the attacker fetches the URL. The server fetches it, from the server's network position, which is why the attacker reaches internal systems they could not reach directly.
  • Missing the cloud-metadata case. SSRF to the metadata service can retrieve the server's cloud credentials, often the most severe outcome, and it is why SSRF rose with cloud adoption.
  • Relying on a deny-list of internal addresses. Attackers use encodings and redirects to reach blocked addresses; use an allow-list of permitted destinations as the primary fix.
  • Following redirects. An allow-listed URL can redirect to a blocked internal one; do not follow redirects to unauthorised destinations.
  • Ignoring network controls. Segmentation and egress filtering limit what a successful SSRF reaches; they are defence in depth.
  • Thinking the reclassification changes the attack. Folding SSRF into Broken Access Control is a heading change reflecting that it is a request reaching an unauthorised destination; the attack and defences are unchanged.

Quick revision

  • SSRF: the application is induced to make a server-side request to an attacker-chosen URL, so the server fetches it from its own network position, reaching internal services, the server's local services, and the cloud metadata service (which can yield the server's credentials) that the attacker cannot reach directly. The server becomes the attacker's proxy.
  • Blind SSRF: the request is made but the response is not returned to the attacker; less powerful, still dangerous.
  • Reclassified from its own 2021 category into Broken Access Control in 2025, because it is fundamentally a request reaching an unauthorised destination.
  • Defences: allow-list permitted destinations (primary), block internal and metadata addresses (supplement, weaker), do not follow redirects, and segment the network and filter egress so a successful SSRF reaches little; protect the cloud metadata service.
munotes.in430

Server-Side Request Forgery

Test yourself

  1. What is server-side request forgery, and why is it powerful?

It is an attack in which an application is induced to make a request to a URL the attacker chose, so the server fetches it on the attacker's behalf. It is powerful because the server sits inside the organisation's network and can reach things the attacker cannot: internal services and administrative interfaces not exposed to the internet, the server's own local services, and the cloud metadata service, so the attacker uses the server as a proxy to reach the internal network.

  1. Why is the cloud metadata case particularly severe?

Because cloud platforms expose to a server a special internal address that returns the server's configuration and often its credentials, and an SSRF that reaches this address can retrieve those cloud credentials. That is a severe escalation, since it hands the attacker the server's identity in the cloud environment, and it is why SSRF rose to prominence as applications moved to the cloud.

  1. Why is SSRF classified under Broken Access Control in the 2025 edition?

Because it is fundamentally a request reaching a resource it should not be allowed to reach: the server accesses an internal destination the request should not have been authorised to reach, which is an access-control failure. Grouping it under Broken Access Control reflects this, and the reclassification changes the heading, not the attack or its defences, illustrating that OWASP categories are ways of organising rather than fixed truths.

  1. Why is an allow-list a better defence than blocking internal addresses?

Because blocking internal addresses is a deny-list, and attackers can reach blocked addresses using alternative encodings, address formats, or redirects, so it is fragile in the same way filtering a dangerous pattern is fragile. An allow-list of the specific destinations the feature legitimately needs constrains the server to known-good targets and rejects everything else, which is robust, with the internal-address blocking used only as a supplement.

  1. What network controls limit the impact of a successful SSRF, and to what principle do they correspond?

Segmenting the network so the application server cannot reach sensitive internal services it does not need, using the hardened cloud metadata service and restricting access to it, and applying egress filtering so the server cannot make arbitrary outbound requests. These correspond to least privilege and segmentation applied to the server's network reach, ensuring that even a successful SSRF reaches little, as defence in depth behind the primary fix of constraining the destination.

Contents This chapter on its own page

munotes.in431

Chapter Ninety-Three

Input Validation: the Thread Through the Whole List

Syllabus topic Module 2, "Web Application Threats and OWASP Vulnerabilities: ... input validation flaws"

In one line

Most of the OWASP Top 10 reduces to trusting input or context that should have been checked. Input validation, checking that input is what is expected, is the recurring supporting defence, but it is not the primary fix for injection and its relatives: the primary fix is neutralising input for the specific context where it is used.

In examination wording: input validation is the practice of verifying that input conforms to expected type, length, format and range, rejecting what does not; it reduces attack surface across many vulnerability categories but does not by itself prevent injection, which requires context-specific handling such as parameterised queries or output encoding, so validation is a defence-in-depth layer rather than the primary control.

The thread

The OWASP overview chapter previewed this synthesis: look across the Top 10 and a pattern dominates. Most categories reduce to trusting something that should have been checked:

  • Injection (and its members SQL injection, command injection, cross-site scripting) trusts input as code.
  • Broken Access Control trusts the user's request to be one they are allowed to make.
  • SSRF trusts a user-supplied destination.
  • Cookie manipulation and client-side trust issues trust client-supplied data.
  • Integrity failures trust code or data whose integrity was not verified.
  • Supply-chain failures trust borrowed code.

The unifying failure is misplaced trust: the application treated something as safe or authoritative that an attacker could control, and did not check it. This is the thread MU points at with "input validation flaws", and seeing it turns the Top 10 from ten separate things into instances of one principle: do not trust; verify.

Two defences recur

From the thread, two defences recur across the list, and naming them is the synthesis:

Input validation. Treat all input as untrusted, and verify it is what is expected before using it.

Correct access control. Check, on the server, on every request, that the acting user is permitted the action (the A01 chapter).

This chapter is about the first, and specifically about its precise role, because that role is widely misunderstood.

What input validation is

Input validation checks that input conforms to what the application expects, and rejects what does not:

  • Type: a number where a number is expected, a date where a date is expected.
  • Length: within sensible bounds, rejecting excessively long input.
  • Format: matching an expected pattern (an email shape, a postcode shape).
  • Range: within allowed values (a quantity between 1 and 100, a date not in the future).
  • Allow-list: where the set of valid values is known, accepting only those and rejecting everything else.

The strongest form is the allow-list (also called positive validation): define what is valid and accept only that, rather than trying to enumerate what is invalid (a deny-list, or negative validation). Allow-listing is robust because it does not depend on anticipating every bad input; a deny-list is fragile because an attacker finds an input the list did not anticipate, the recurring "filtering is fragile" lesson from directory traversal, Log4Shell and SSRF. So: validate against what is allowed, not against what is forbidden.

munotes.in432

Input Validation: the Thread Through the Whole List

Input validation reduces attack surface across the whole list: rejecting input that does not fit the expected shape means much malicious input never reaches the vulnerable code at all.

The crucial point: validation is not the primary fix for injection

Here is the point students most often get wrong, and it is the chapter's central correction.

Input validation does not, by itself, prevent injection. It helps, but it is not the primary fix, for two reasons:

  • Valid-looking input can still be malicious in a context. Input that passes validation (a plausible name, a normal-looking string) can still contain characters or content that are dangerous when placed into a query, a command or a page. A name like O'Brien is valid input and contains a character significant to SQL; validation should accept it, and the SQL context must handle it safely. Validation cannot reject everything dangerous to every context without also rejecting legitimate input.
  • The same input is safe in one context and dangerous in another. A string harmless in the page body may be dangerous in a script context; validation on input cannot know which context the data will later be used in, so it cannot neutralise for that context.

So the primary fix for injection is context-specific handling, applied where the input is used:

  • Parameterised queries for SQL, so data can never become query structure (chapter 97).
  • Context-aware output encoding for web pages, so data cannot become script (chapter 89).
  • Safe interfaces for commands, so input is passed as arguments, not as a command string.

And input validation is the supporting layer: it reduces the surface and catches obviously-malformed input, but the context-specific handling is what actually prevents the injection, because it works regardless of what the input contains.

The precise relationship, which is the examinable formulation: validate input on the way in (a supporting layer), and handle it safely for its context on the way out or where it is used (the primary fix). A developer who relies on validation alone is filtering, and filtering is fragile; a developer who parameterises and encodes is safe regardless of the input, and validation makes their surface smaller.

Why not just validate harder?

A student may ask why validation cannot simply be made strict enough to catch everything. The answer is the two reasons above, sharpened: to catch everything dangerous to every context, validation would have to reject all input that could be dangerous anywhere, which would reject vast amounts of legitimate input (every name with an apostrophe, every message with a special character), making the application unusable. The context-specific defences avoid this: they let any input through as data and neutralise it for the specific context, so legitimate input works and malicious input is inert. That is why the division of labour, validate for shape, handle for context, is the right design.

munotes.in433

Input Validation: the Thread Through the Whole List

A worked example, framed defensively

An assessor reviews an application's input handling and states the relationship for the client.

  • The application relies on input filtering to prevent SQL injection, rejecting inputs containing certain characters. Finding: filtering is fragile and rejects legitimate input (a customer named O'Brien cannot register), yet is still bypassable. Fix: use parameterised queries (the primary fix), and validate for shape (a supporting layer) without trying to filter dangerous characters.
  • Input is validated but then placed into a page without encoding. Finding: validation is not the XSS fix; the primary fix is output encoding. Fix: encode on output; keep validation as support.
  • Input is validated with a deny-list of bad patterns. Finding: deny-list is fragile; use an allow-list of valid values where the set is known.
  • The assessor states the rule for the client: validate on the way in for shape, handle safely for context where used; the context-specific handling is the fix, validation supports it.

The report's synthesis is that most of the findings across the OWASP block reduce to misplaced trust, and that the discipline is to validate input and, more importantly, to handle it safely for each context, which is the thread through the whole list.

What beginners get wrong

  • Thinking input validation prevents injection. It supports the defence; the primary fix is context-specific handling (parameterised queries, output encoding, safe interfaces), because valid-looking input can still inject.
  • Trying to filter dangerous characters. Filtering is fragile (attackers find inputs it missed) and rejects legitimate input (names with apostrophes); handle for context instead.
  • Using a deny-list. Enumerating bad inputs fails because attackers find ones you did not anticipate; use an allow-list of valid values.
  • Validating for the wrong thing. Validation checks shape (type, length, format, range); it cannot know the later context, so it cannot neutralise for it.
  • Believing "validate harder" solves it. Catching everything dangerous to every context would reject legitimate input and make the app unusable; the context-specific defences let input through as data and neutralise it per context.
  • Missing the thread. Most of the Top 10 is misplaced trust; the discipline is do not trust, verify, with input validation and access control recurring.
munotes.in434

Input Validation: the Thread Through the Whole List

Quick revision

  • Most of the OWASP Top 10 reduces to misplaced trust: trusting input as code (injection), the user's request (access control), a supplied destination (SSRF), client data (manipulation), or unverified code/data (integrity, supply chain). The principle: do not trust; verify.
  • Two recurring defences: input validation and correct server-side access control.
  • Input validation checks type, length, format, range, preferring an allow-list (accept the valid) over a deny-list (reject the invalid), which is fragile. It reduces attack surface across the list.
  • But validation is not the primary fix for injection: valid-looking input can still be malicious in a context, and the same input is safe in one context and dangerous in another. The primary fix is context-specific handling (parameterised queries, output encoding, safe interfaces); validation is the supporting layer.
  • The rule: validate for shape on the way in, handle safely for context where used.

Test yourself

  1. What single thread runs through most of the OWASP Top 10, and what principle does it yield?

Misplaced trust: most categories reduce to the application trusting something an attacker could control without checking it, injection trusts input as code, broken access control trusts the user's request, SSRF trusts a supplied destination, and integrity and supply-chain failures trust unverified code or data. The principle is do not trust, verify, from which two recurring defences follow: input validation and correct server-side access control.

  1. What does input validation check, and why is an allow-list preferable to a deny-list?

It checks that input conforms to what is expected in type, length, format and range, rejecting what does not. An allow-list, accepting only known-valid values, is preferable to a deny-list, rejecting known-bad ones, because a deny-list depends on anticipating every malicious input and an attacker finds one it did not anticipate, whereas an allow-list constrains input to known-good values and is robust regardless of what an attacker tries.

  1. Why does input validation not, by itself, prevent injection?

For two reasons: valid-looking input can still be malicious in a particular context, since input that passes validation, such as a legitimate name containing an apostrophe, can contain content dangerous when placed into a query or page; and the same input may be safe in one context and dangerous in another, so validation performed on input cannot know the later context and cannot neutralise for it. Preventing injection therefore requires handling the input safely for the specific context where it is used.

  1. What is the correct relationship between input validation and the context-specific defences?

Validate input on the way in as a supporting layer that reduces attack surface and rejects obviously-malformed input, and handle input safely for its context where it is used as the primary fix, using parameterised queries for SQL, context-aware output encoding for web pages, and safe interfaces for commands. The context-specific handling actually prevents the injection because it works regardless of the input's content, while validation makes the surface smaller.

munotes.in435

Input Validation: the Thread Through the Whole List

  1. Why can validation not simply be made strict enough to catch every dangerous input?

Because to catch everything dangerous to every context, validation would have to reject all input that could be dangerous anywhere, which would reject vast amounts of legitimate input, such as every name with an apostrophe or message with a special character, making the application unusable. The context-specific defences avoid this by allowing any input through as data and neutralising it only for the specific context, so legitimate input works and malicious input is rendered inert.

Contents This chapter on its own page

munotes.in436

Chapter Ninety-Four

SQL Injection: How Input Becomes Logic

Syllabus topic Module 2, "SQL Injection - Attack Logic and Prevention: Understand SQL injection mechanisms, query manipulation techniques, database vulnerabilities"

In one line

SQL injection happens when an application builds a database query by combining fixed query text with user input, so that crafted input becomes part of the query's logic instead of being treated as a value. The attacker rewrites the question the application asks the database.

In examination wording: SQL injection is an attack in which untrusted input is incorporated into an SQL statement such that it alters the statement's structure or logic, enabling an attacker to read, modify or destroy data, or bypass authentication; it arises from constructing queries by combining query text with input rather than separating the two.

Why SQL injection matters

SQL injection has been near the top of the OWASP list for two decades, and MU gives it its own topic, for a reason worth stating: it is both catastrophic and completely preventable.

Catastrophic, because a database usually holds everything valuable: user accounts, personal data, orders, and, if stored wrongly, passwords. A successful injection can read all of it, change it, delete it, and sometimes bypass the login entirely. Completely preventable, because a single correct coding habit, parameterised queries (chapter 97), removes the entire class.

The gap between how damaging it is and how easily it is prevented is exactly why it persists: it takes only one query built the wrong way, anywhere in a large application, to reintroduce it. So a student must understand the mechanism precisely, to recognise the wrong way and to apply the fix everywhere.

The database and the query, briefly

An application stores its data in a database, and it asks the database questions and gives it instructions in a language called SQL. A query is a statement in that language: "find the user whose name is this", "insert this order", "update this record". The database interprets the SQL and does what it says.

The application builds these queries as it runs, filling in the specific values, the name to look up, the order to insert, from the current request. How it fills in those values is where SQL injection lives.

The mechanism: combining text with input

Consider a login that looks up a user by the name they typed. The application means the typed name to be a value: the name to search for. The query has a fixed part (the developer's SQL: find a user where the name equals ...) and a variable part (the value: the name typed).

The vulnerability is building the query by pasting the input directly into the query text, so that the fixed SQL and the user's input become one combined string that is sent to the database. When that happens, the database receives a single statement and cannot tell which part was the developer's instruction and which was the user's data. It interprets the whole thing as SQL.

munotes.in437

SQL Injection: How Input Becomes Logic

So input that contains SQL punctuation and keywords is read as part of the query, not as a value. The special characters that mean something in SQL, quotation marks that end a text value, and keywords that add conditions or commands, let crafted input close the value the developer intended and add logic of its own. The classic result is input crafted so that the query's condition is always true, or so that extra commands are appended.

The essence, and the phrase to carry: the attacker has not broken into the database; they have rewritten the question the application asks it, because the application let the input change the query's structure. That is what "query manipulation" means: the input stops being data and becomes logic.

What it achieves

Once the attacker can change the query's logic, the consequences span the database:

  • Authentication bypass: input that makes the login query's condition always true logs the attacker in without a valid password, because the query now returns a user regardless of the credentials.
  • Data disclosure: input that extends the query to return data it was never meant to return, including other tables (the union technique of the next chapter).
  • Data modification or destruction: input that appends a command to change or delete data, since the database executes what the combined statement tells it.
  • Further compromise: in some configurations, reaching the operating system or other systems through database features, escalating a database flaw toward server compromise.

The severity depends partly on what the database account can do, which is why least privilege on that account (chapter 98) limits the damage.

Why it is an injection, and shares the family's shape

SQL injection is the archetypal member of the injection family (chapter 87): untrusted input crossing into an interpreter (the database) such that it becomes code (SQL) rather than data (a value). It shares the family's root cause, building instructions by combining fixed text with input, and the family's fix, keep input strictly as data in its context, which for SQL is the parameterised query. Recognising it as injection means a student who understands the category understands SQL injection's mechanism immediately.

A worked example, framed defensively

An assessor examines how an application builds queries, using benign test inputs against a test account and a test database, never destructive input against real data.

  • The login builds its query by combining the SQL with the typed username and password. A benign test input containing SQL punctuation changes how the query is interpreted, confirming the input is not kept as a value. SQL injection in the login, potentially allowing authentication bypass. Fix: parameterised queries (chapter 97).
  • The product search builds its query the same way; a test input alters the query's behaviour. SQL injection in search, potentially allowing data disclosure.
  • The assessor confirms the mechanism, that input becomes part of the query's logic, without extracting real data or altering anything, which is the minimum needed to establish the finding.
munotes.in438

SQL Injection: How Input Becomes Logic

The report explains that these are the same defect, input becoming query logic, and that the fix is one habit applied to every query. The assessor is careful to use benign markers that demonstrate the input is interpreted as SQL, not payloads that read or damage data, which is the ethical way to prove SQL injection.

What beginners get wrong

  • Thinking the attacker breaks into the database. They rewrite the query the application sends, because the application let input change the query's structure; the database faithfully executes the altered query.
  • Missing the root cause. It is combining fixed query text with input into one string, so the database cannot separate code from data.
  • Believing only the login is at risk. Any query built by combining text with input is vulnerable: search, filters, sorting, anywhere input reaches a query.
  • Underrating it. It can bypass authentication, read, modify or destroy the whole database, and sometimes reach the server; it is both catastrophic and common.
  • Not recognising it as injection. It is the archetypal injection: input becoming code in an interpreter, here the database.
  • Testing with destructive input. Establish the mechanism with benign markers; do not read or damage real data to prove the flaw.

Quick revision

  • SQL injection: the application builds a query by combining fixed SQL with input into one string, so the database cannot tell code from data, and crafted input containing SQL punctuation and keywords becomes part of the query's logic ("query manipulation").
  • The essence: the attacker rewrites the question the application asks the database; they do not break into it.
  • Achieves: authentication bypass (a condition made always true), data disclosure (extending the query), modification or destruction (appending commands), and sometimes further compromise. Severity depends partly on the database account's privileges.
  • It is the archetypal injection: untrusted input becoming code in an interpreter; root cause and fix are the family's (parameterised queries, chapter 97).

Test yourself

  1. Explain the mechanism of SQL injection.

The application builds a database query by combining fixed query text written by the developer with user input, pasting the input directly into the query so that the two become one combined string sent to the database. The database cannot distinguish the developer's instructions from the user's data and interprets the whole statement as SQL, so input containing SQL punctuation and keywords becomes part of the query's logic, letting the attacker close the intended value and add logic of their own.

munotes.in439

SQL Injection: How Input Becomes Logic

  1. What does "query manipulation" mean, and why is it not "breaking into" the database?

Query manipulation means the attacker's input changes the structure or logic of the SQL statement the application sends, for example making a condition always true or adding a command, so the input stops being data and becomes part of the query. It is not breaking into the database because the database faithfully executes the query it receives; the attacker has rewritten the question the application asks, exploiting that the application let input change the query's structure.

  1. What can SQL injection achieve?

Authentication bypass, by making a login query's condition always true so it returns a user without valid credentials; data disclosure, by extending the query to return data it was not meant to; data modification or destruction, by appending commands to change or delete data; and, in some configurations, further compromise reaching the operating system or other systems. The severity depends partly on what the database account is permitted to do.

  1. Why is SQL injection considered the archetypal injection attack?

Because it is exactly the injection mechanism, untrusted input crossing into an interpreter such that it becomes code rather than data, with the database as the interpreter and SQL as the code. It shares the injection family's root cause of building instructions by combining fixed text with input, and its fix of keeping input strictly as data in its context, which for SQL is the parameterised query.

  1. Why does SQL injection persist despite being completely preventable?

Because prevention requires that every query in an application be built the correct way, and it takes only one query anywhere in a large application built by combining text with input to reintroduce the flaw. The gap between how catastrophic it is, capable of reading, altering or destroying the whole database and bypassing authentication, and how easily a single overlooked query recreates it, is why it remains common despite a known, definitive fix.

Contents This chapter on its own page

munotes.in440

Chapter Ninety-Five

The Types: In-Band, Union-Based and Error-Based

Syllabus topic Module 2, "SQL Injection - Attack Logic and Prevention: ... query manipulation techniques, database vulnerabilities"

In one line

SQL injection is classified by how the attacker gets data back. In-band returns it through the same channel: union-based extends the query to include extra data in the results, and error-based reads data out of the database's error messages. Both need the attacker to see the response.

In examination wording: in-band SQL injection retrieves data through the same channel used to inject, principally by union-based techniques that append a second query result to the intended one, and by error-based techniques that provoke the database into revealing data within error messages; both require the attacker to observe the application's response.

Classifying by how data comes back

The previous chapter established that an attacker can change the query's logic. This chapter is about how they get information out, because changing the query is only useful if the attacker can see the result, and the ways of seeing it define the types.

The top-level split is:

  • In-band: the data comes back through the same channel the attacker used, that is, in the application's normal response, which they can see. This chapter.
  • Blind (inferential): the data does not come back directly; the attacker infers it from the application's behaviour. The next chapter.

In-band is the easier and more direct, and it has two main techniques.

Union-based injection

The most direct way to extract data. It uses a feature of SQL that lets the results of one query be combined with the results of another into a single result set.

The idea, at concept level: the application's query returns some rows (the products matching a search, say), and the application displays them. If the attacker can inject into that query, they can append their own query whose results are combined with the intended ones, so that the attacker's chosen data appears in the same results the application displays.

So the search that was meant to show products can be made to show, in the product list, data from another table entirely, user accounts, for instance, because the attacker appended a query selecting that data and combined it into the displayed results. The application shows it, because as far as it knows it is showing the query's results, not knowing the query was extended.

Union-based injection is powerful because it lets the attacker pull arbitrary data into the visible response, reading tables the feature was never meant to touch. It requires the injected query to match the structure of the original in certain ways (the same number of columns, compatible types), which the attacker works out, but once matched it is a direct data-exfiltration technique.

Error-based injection

The second in-band technique, used when the data cannot be pulled directly into the results but the application shows error messages.

munotes.in441

The Types: In-Band, Union-Based and Error-Based

The idea: the attacker crafts input that causes the database to produce an error, and arranges for the data they want to be included in the error message. If the application displays database errors to the user (the verbose-errors misconfiguration), the attacker reads the data out of the error text.

For example, an attacker can provoke an error whose message contains the result of a sub-query, so that instead of a normal response they receive an error saying, in effect, "error involving the data they wanted". The data is exfiltrated through the error channel rather than the results channel.

Error-based injection depends entirely on the application exposing database errors to the user. If the application returns generic errors and logs the detail server-side (the correct configuration from the web-server block), error-based injection has no channel, which is the defensive lesson.

The defensive lesson: verbose errors are a security setting

Error-based injection makes concrete a point the web-server block stated: a verbose database error is not a convenience, it is a disclosure channel. An application that shows database errors to users:

  • Hands an attacker a channel for error-based injection.
  • Discloses the database structure, table and column names, and query fragments, which aids all injection.
  • Reveals the database software and version (fingerprinting).

So the finding "the application displays database errors" is a security finding, and the fix is the web-server block's: generic error pages for users, detailed errors to server-side logs. This does not fix the injection (parameterised queries do), but it removes the error-based channel and the structural disclosure, which is defence in depth.

In-band against blind, previewing the next chapter

The types matter because they determine what an attacker can do and what a defender should watch for. In-band injection (union and error) requires the attacker to see the response, either the results or the errors. When the application returns neither the injected data in its results nor database errors, the attacker cannot use in-band techniques, and must fall back on blind injection, inferring data from behaviour, which is the next chapter and is slower but still effective. So a defender who removes the error channel (generic errors) and does not reflect injected data has not fixed the injection but has forced the attacker into the harder blind techniques, which is worth doing as defence in depth while the real fix (parameterised queries) is applied.

A worked example, framed defensively

An assessor tests an application's SQL injection, having confirmed the mechanism, using benign techniques against a test database.

  • The search results can be made, with a union technique, to include data from another table, confirming union-based injection and that arbitrary data could be exfiltrated. The assessor demonstrates the technique against a harmless test table, not by reading real user data.
  • The application displays database errors to users, and a crafted input produces an error containing sub-query output, confirming error-based injection and structural disclosure. Two findings: the injection, and the verbose errors as a disclosure channel.
  • The assessor notes that even without the union channel, the error channel alone would allow extraction, and that removing verbose errors (generic pages, detail to logs) closes the error channel and the structural disclosure.
munotes.in442

The Types: In-Band, Union-Based and Error-Based

Recommendations: the definitive fix is parameterised queries (chapter 97), which removes the injection regardless of type; and, as defence in depth, generic error pages to close the error-based channel and the structural disclosure. The assessor establishes the types with benign demonstrations, never by exfiltrating real data.

What beginners get wrong

  • Not distinguishing how data comes back. The types are classified by the channel: in-band (results or errors) against blind (inference). This determines the attacker's approach.
  • Thinking union-based injection only reads the current table. It combines a second query's results into the displayed ones, so it can read arbitrary tables the feature never touched.
  • Treating verbose errors as a convenience. They are a disclosure channel enabling error-based injection and revealing the database structure; generic errors for users, detail to logs.
  • Believing generic errors fix the injection. They close the error-based channel and structural disclosure but do not fix the injection; parameterised queries do. Generic errors are defence in depth.
  • Assuming no visible errors and no reflected data means safety. It forces the attacker to blind techniques (next chapter), which are slower but still effective; the injection is still there.

Quick revision

  • SQL injection types are classified by how data comes back: in-band (same channel, attacker sees it) against blind (inferred from behaviour, next chapter).
  • Union-based (in-band): appends a second query whose results are combined into the displayed results, letting the attacker pull arbitrary data (other tables) into the visible response.
  • Error-based (in-band): provokes a database error containing the wanted data, read from the error message; depends on the application displaying database errors.
  • Defensive lesson: verbose database errors are a disclosure channel (enabling error-based injection and revealing structure); fix with generic error pages, detail to logs. This is defence in depth, not the injection fix.
  • Removing the error and reflection channels forces the attacker to blind techniques (harder), while parameterised queries remove the injection itself.

Test yourself

  1. On what basis are SQL injection types classified, and what is the top-level split?

They are classified by how the attacker retrieves the data, since changing the query is only useful if the result can be seen. The top-level split is in-band, where the data comes back through the same channel as the injection in the application's visible response, against blind or inferential, where the data does not come back directly and the attacker infers it from the application's behaviour.

munotes.in443

The Types: In-Band, Union-Based and Error-Based

  1. How does union-based injection extract data, and why is it powerful?

It uses SQL's ability to combine the results of two queries into one result set: the attacker appends their own query, whose results are combined with the intended ones, so their chosen data appears in the results the application displays. It is powerful because it lets the attacker pull arbitrary data, including from tables the feature was never meant to touch, into the visible response, which the application shows believing it is displaying its own query's results.

  1. How does error-based injection work, and on what does it depend?

The attacker crafts input that causes the database to produce an error whose message includes the data they want, for example an error containing the result of a sub-query, so the data is exfiltrated through the error text. It depends entirely on the application displaying database errors to the user; if the application returns generic errors and logs the detail server-side, error-based injection has no channel.

  1. Why is a verbose database error a security finding, and what is the fix?

Because it provides a channel for error-based injection and discloses the database structure, table and column names and query fragments, and the database software and version, all of which aid an attacker. The fix is to return generic error pages to users while logging the detailed errors server-side, which removes the error-based channel and the structural disclosure; it is defence in depth and does not itself fix the injection, which requires parameterised queries.

  1. What is the effect of removing the error and reflection channels without fixing the injection?

It forces the attacker to fall back on blind injection, inferring data from the application's behaviour rather than reading it from results or errors, which is slower and more laborious but still effective. The injection itself remains, so this is defence in depth that raises the attacker's cost while the definitive fix, parameterised queries, is applied to remove the vulnerability regardless of type.

Contents This chapter on its own page

munotes.in444

Chapter Ninety-Six

Blind SQL Injection: Boolean and Time-Based

Syllabus topic Module 2, "SQL Injection - Attack Logic and Prevention: ... query manipulation techniques, database vulnerabilities"

In one line

Blind SQL injection extracts data when the application returns neither the data nor errors: the attacker asks the database yes-or-no questions and infers the answer from how the application behaves, either whether the page changes (boolean) or how long it takes to respond (time-based), one bit at a time.

In examination wording: blind, or inferential, SQL injection retrieves data without the application returning it directly, by injecting queries whose truth or falsity produces an observable difference in the application's response; boolean-based blind injection observes differences in the returned page, and time-based blind injection observes differences in response time induced by conditional delays.

Why blind injection exists

The previous chapter's in-band techniques needed the attacker to see the data, in the results or in error messages. A natural defensive instinct is therefore to hide the output: return a generic error, do not reflect injected data, and assume the injection is thereby neutralised.

Blind injection is the demonstration that this assumption is wrong, and that is its main lesson. Even when the application returns no data and no errors, an attacker can still extract information, because the application's behaviour differs depending on whether an injected condition is true or false, and that difference is enough to infer data one bit at a time.

So blind injection is the chapter that proves hiding the output is not a fix. The vulnerability is still there, the query is still manipulable, and the attacker simply uses a slower, indirect method to read the data. This is the strongest argument in the block for the real fix being parameterised queries, which remove the manipulation itself, rather than any attempt to hide the result.

Boolean-based blind injection

The attacker turns data extraction into a series of yes-or-no questions, each answered by whether the application's response changes.

The idea: the attacker injects a condition into the query, and the injected condition is either true or false depending on the data they are trying to learn. If the application behaves one way when the condition is true and another way when it is false, even a small difference such as whether a result is returned or the page renders slightly differently, then the attacker learns the answer to that yes-or-no question by observing which behaviour occurred.

By asking a sequence of such questions, the attacker extracts data one bit at a time: "is the first character of the password hash greater than this?", "is it in this range?", narrowing down each character through repeated questions, each answered by the observable difference. It is laborious, one bit per request, but it is automatable, so tools do it at machine speed, and the whole database can be read through a channel that returns no data at all, only a difference in behaviour.

munotes.in445

Blind SQL Injection: Boolean and Time-Based

The defensive point: any observable difference in behaviour between a true and a false injected condition is a channel. Making responses identical regardless is hard and is not the fix; the fix is to prevent the injection.

Time-based blind injection

Used when there is no observable difference in the response at all, not even a subtle one: the application returns the same thing whether the injected condition is true or false. Even then, the attacker has one more channel: time.

The idea: the attacker injects a condition combined with an instruction to delay the database's response if the condition is true. So if the condition is true, the response takes noticeably longer; if false, it returns promptly. The attacker learns the answer to the yes-or-no question by how long the response took, not by its content.

Time-based injection is the last resort and the slowest, since each question requires waiting for a delay, but it works even when the application's response is completely uniform, because the attacker introduces the observable difference themselves, as a delay. It proves the point most starkly: even an application that reveals nothing in its responses can be read through timing, so hiding the output cannot be the fix.

Why blind injection settles the argument

The block has repeatedly said the fix for SQL injection is parameterised queries, not hiding the output. Blind injection is why, and a student should be able to make the argument:

  • In-band techniques are defeated by hiding the data and errors, so a defender might think that suffices.
  • Boolean-based blind injection defeats that, by inferring data from any behavioural difference.
  • Time-based blind injection defeats even a uniform response, by introducing a timing difference.

So there is no way to hide the output well enough to stop a determined attacker, because the attacker can manufacture the channel (a delay) if the application does not provide one. The only reliable fix is to prevent the query being manipulated in the first place, which is the parameterised query of the next chapter. Blind injection is the proof that the defence must be at the injection, not at the output.

A worked example, framed defensively

An assessor tests an application that returns generic errors and does not reflect data, to determine whether it is nonetheless injectable, using benign conditions against a test database.

  • Injecting a condition that is true, the page behaves one way; injecting a false condition, it behaves differently (a result is returned or not). Boolean-based blind injection confirmed: the application leaks one bit per request through its behaviour, so data could be extracted despite returning no data or errors.
  • Where the response is uniform, injecting a condition combined with a delay makes the response slow when the condition is true and prompt when false. Time-based blind injection confirmed: data could be extracted through timing alone.
  • The assessor demonstrates the channels with benign conditions (is a harmless test value true) rather than extracting real data, which is the minimum needed to prove the finding.
munotes.in446

Blind SQL Injection: Boolean and Time-Based

The report's central point is that the application's generic errors and hidden data do not protect it: it is fully injectable through blind techniques, and the only fix is parameterised queries (chapter 97). This is the finding that corrects a client who believed hiding output was sufficient.

What beginners get wrong

  • Thinking hiding the data and errors fixes injection. Blind injection extracts data with no data and no errors returned, so hiding output is not a fix; parameterised queries are.
  • Believing blind injection is impractical because it is slow. It is one bit per request but automatable, so tools read the whole database at machine speed.
  • Confusing boolean-based and time-based. Boolean-based infers from a difference in the response; time-based infers from a difference in response time, used when the response is uniform.
  • Assuming a uniform response is safe. Time-based injection introduces the difference itself as a delay, so even a completely uniform response is exploitable.
  • Missing the argument. Blind injection proves the defence must be at the injection (parameterised queries), not at the output, because the attacker can manufacture a channel.
  • Testing by extracting real data. Demonstrate the channel with benign conditions; do not read real data to prove blind injection.

Quick revision

  • Blind (inferential) SQL injection: extracts data when the application returns neither data nor errors, by inferring answers to yes-or-no questions from the application's behaviour, one bit at a time (laborious but automatable).
  • Boolean-based: the injected condition being true or false produces an observable difference in the response (a result returned or not, the page changing); the attacker reads the difference.
  • Time-based: used when the response is uniform; the attacker injects a condition combined with a delay if true, and reads the answer from how long the response took, manufacturing the channel themselves.
  • The argument: in-band is defeated by hiding output, boolean-based defeats that, time-based defeats even a uniform response, so hiding output can never suffice; the fix must be at the injection (parameterised queries), not the output.

Test yourself

  1. What is blind SQL injection, and what does its existence prove?

It is SQL injection that extracts data when the application returns neither the data nor error messages, by inferring the answers to yes-or-no questions from differences in the application's behaviour, one bit at a time. Its existence proves that hiding the output, returning generic errors and not reflecting data, does not fix the injection, because the attacker can still read the database through behavioural or timing channels, so the fix must prevent the query manipulation itself.

munotes.in447

Blind SQL Injection: Boolean and Time-Based

  1. How does boolean-based blind injection extract data?

The attacker injects a condition into the query that is true or false depending on the data being sought, and observes that the application behaves one way when the condition is true and another when it is false, for example returning a result or not. By asking a sequence of such yes-or-no questions and reading which behaviour occurred each time, the attacker narrows down and extracts the data one bit at a time, a process that is laborious but automatable.

  1. When is time-based blind injection used, and how does it work?

It is used when the application's response is uniform, showing no observable difference whether the injected condition is true or false. The attacker injects a condition combined with an instruction to delay the database's response if the condition is true, so a true condition makes the response noticeably slower and a false one returns promptly, and the attacker infers the answer from how long the response took, having introduced the observable difference themselves as a delay.

  1. Why does blind injection settle the argument that the fix must be parameterised queries rather than hiding output?

Because it shows there is no way to hide the output well enough to stop a determined attacker: in-band techniques are defeated by hiding data and errors, boolean-based blind injection defeats that by inferring from any behavioural difference, and time-based blind injection defeats even a completely uniform response by manufacturing a timing channel. Since the attacker can always create a channel, the only reliable defence is to prevent the query from being manipulated in the first place, which parameterised queries do.

  1. Why is the slowness of blind injection not a reassurance?

Because although each yes-or-no question requires a separate request and extracts only one bit, the process is fully automatable, so tools perform it at machine speed and can read an entire database despite the application returning no data or errors. The laboriousness is borne by software, not by the attacker, so a slow channel is still a complete data-exfiltration channel.

Contents This chapter on its own page

munotes.in448

Chapter Ninety-Seven

Prevention: the Parameterised Query

Syllabus topic Module 2, "SQL Injection - Attack Logic and Prevention: ... database vulnerabilities, and secure coding practices"

In one line

The definitive fix for SQL injection is the parameterised query (prepared statement): send the query structure and the data to the database separately, so that the data can never become part of the structure, and any input, however crafted, is treated as a value.

In examination wording: a parameterised query, or prepared statement, prevents SQL injection by sending the query's structure to the database with placeholders and supplying the data values separately, so that the database compiles the structure before receiving the values and treats each value strictly as data, making it impossible for input to alter the query's logic.

Why the fix is not filtering

The block has repeatedly rejected filtering, and this chapter states why one last time before giving the real fix.

The tempting response to SQL injection is to filter the input: reject or escape the characters that are dangerous in SQL. This is fragile, for the reasons the injection and traversal chapters gave: attackers find encodings and forms the filter did not anticipate, and, worse, legitimate input contains dangerous characters (a name like O'Brien contains a quote), so a filter strict enough to be safe rejects real users, and a filter loose enough to accept real users is bypassable. Filtering is the wrong level.

The right fix works at a different level: do not build the query out of input at all, so there is nothing to filter, because the input never becomes part of the query's structure.

How a parameterised query works

The insight is the one from the injection-category chapter: the vulnerability is that the query structure and the data are combined into one string, so the database cannot tell them apart. A parameterised query keeps them separate.

The query is written with placeholders where the values go, and the values are supplied separately as parameters. Then:

  1. The database receives the query structure first, with the placeholders, and compiles it, fixing the structure, before it has seen any value.
  2. The values are supplied separately and slotted into the placeholders as pure data, after the structure is already fixed.

Because the structure is compiled before any value is seen, no value can change the structure. The value is data by construction: it is placed into a slot in an already-fixed query, not concatenated into the query text. So an input that against a concatenated query would have been read as SQL is, against a parameterised query, just an odd value that matches nothing, because it is searched for as a literal value, not interpreted as SQL.

This is the definitive fix because it addresses the mechanism directly: the injection worked by input becoming structure, and the parameterised query makes that impossible by fixing the structure before the value arrives. It does not depend on anticipating dangerous inputs (as filtering does); it works for any input, because every input is treated as data.

munotes.in449

Prevention: the Parameterised Query

The demonstration

This program demonstrates the defence: a classic injection string is passed as a parameter and treated as an ordinary (nonexistent) value, matching nothing, with the table untouched. It is safe and self-contained: an in-memory database, benign data, and it attacks nothing. The vulnerable concatenation pattern is described in prose above and deliberately not run.

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (id INTEGER, name TEXT, role TEXT)")
db.executemany("INSERT INTO users VALUES (?, ?, ?)",
               [(1, "asha", "student"), (2, "ravi", "student"), (3, "admin", "staff")])
db.commit()


def find_user(name):
    # The safe way: the value is passed as a PARAMETER (?), never built into
    # the SQL text. The database treats it strictly as data, never as code.
    cur = db.execute("SELECT id, name, role FROM users WHERE name = ?", (name,))
    return cur.fetchall()


# A normal lookup works.
print("normal input 'asha':", find_user("asha"))

# A classic injection string. Because it is a parameter, it is treated as a
# literal name to search for, not as SQL. There is no user literally called
# "' OR '1'='1", so it matches nothing. The attack is neutralised.
print("injection string   :", find_user("' OR '1'='1"))

# Proof the whole table was not returned: still three rows, all intact.
print("row count in table :", db.execute("SELECT COUNT(*) FROM users").fetchone()[0])
normal input 'asha': [(1, 'asha', 'student')]
injection string   : []
row count in table : 3

Read the output. The normal name returns its one row. The injection string, which against a concatenated query would have forced the condition true and returned every row, here returns nothing, because the database searched for a user whose name is literally that odd string and found none. The table still holds its three rows: nothing was disclosed, changed or destroyed. The parameter boundary did the whole job, with no filtering of the input at all. That is the definitive fix, shown rather than asserted.

Applying it everywhere

The fix is complete only if applied to every query, without exception, because a single concatenated query anywhere is a vulnerability. So the secure-coding practice is:

  • Use parameterised queries for every query that involves any input, everywhere in the application.
  • Where an application uses stored procedures, they must also be written to use parameters, not to build query text from input inside the procedure, or the injection simply moves into the procedure.
  • Where an object-relational mapping or query builder is used, it typically parameterises automatically, which is one of its benefits, but the raw-query escape hatch must not be used with input concatenated in.
  • The one case that cannot be parameterised, an identifier such as a table or column name chosen by input (parameters are for values, not identifiers), is handled by an allow-list: map the input to one of a fixed set of permitted identifiers, never build it from input. This is the same allow-list principle as elsewhere.
munotes.in450

Prevention: the Parameterised Query

The rule to carry: parameterise every query; where a value cannot be a parameter (an identifier), use an allow-list; never concatenate input into query text.

A worked example, framed defensively

An assessor reviews an application's queries after confirming injection.

  • The login and search queries are built by concatenating input into the SQL. Fix: rewrite as parameterised queries. Verified with a benign injection-shaped input, which now matches nothing, exactly as the demonstration shows.
  • A stored procedure builds query text from input internally. Finding: the injection is inside the procedure; parameterising the call does not help. Fix: rewrite the procedure to use parameters.
  • A sort feature takes a column name from input and concatenates it (an identifier, which cannot be a parameter). Fix: map the input to an allow-list of permitted column names.
  • The assessor confirms that after these changes, injection-shaped inputs are treated as data everywhere and match nothing, and that the fix is uniform across the application.

The report's headline is one habit: parameterise every query, use an allow-list for identifiers, and never concatenate input into SQL, which removes the whole class regardless of injection type, including the blind types the previous chapter showed hiding output cannot stop. The assessor verified with benign inputs, never destructive ones.

What beginners get wrong

  • Trying to fix injection by filtering or escaping input. Filtering is fragile and rejects legitimate input; the parameter boundary works for any input and is the fix.
  • Parameterising most queries but not all. One concatenated query is a vulnerability; it must be every query, without exception.
  • Thinking stored procedures are automatically safe. A procedure that builds query text from input is injectable inside the procedure; it must use parameters.
  • Concatenating an identifier because it cannot be a parameter. Table and column names from input use an allow-list, not concatenation.
  • Using an ORM's raw-query escape hatch with concatenated input. That reintroduces the flaw; use the parameterised interface.
  • Believing the fix depends on anticipating dangerous inputs. It does not: every input is treated as data, so it works regardless of what the input contains, which filtering cannot claim.

Quick revision

  • The definitive fix is the parameterised query (prepared statement): send the query structure with placeholders and the values separately; the database compiles the structure before seeing any value, so no value can change the structure, and any input is treated as a literal value.
  • Filtering is rejected: fragile (bypassable) and rejects legitimate input (names with quotes); the parameter boundary works for any input without anticipating dangerous ones.
  • Demonstrated: an injection string passed as a parameter matches nothing, the table intact, with no input filtering.
  • Apply to every query; write stored procedures with parameters; ORMs parameterise but do not misuse the raw escape hatch; for an identifier (table/column name, which cannot be a parameter) use an allow-list. Never concatenate input into SQL.
munotes.in451

Prevention: the Parameterised Query

Test yourself

  1. How does a parameterised query prevent SQL injection?

It sends the query's structure to the database with placeholders where values go, and supplies the values separately as parameters. The database compiles the structure before it receives any value, so the structure is fixed first, and the values are then slotted into the placeholders as pure data. Because no value is seen until the structure is already fixed, no input can change the structure, so an injection string is treated as a literal value that matches nothing rather than as SQL.

  1. Why is the parameterised query preferred over filtering or escaping input?

Because filtering is fragile, attackers find encodings and forms it did not anticipate, and it rejects legitimate input such as names containing quotes, so a filter safe enough to block attacks also blocks real users. The parameterised query works at a different level, treating every input as data by construction, so it neutralises any input regardless of its content without needing to anticipate dangerous inputs, which is why it is the definitive fix.

  1. In the demonstration, why does the injection string return no rows rather than the whole table?

Because it is passed as a parameter, so the database searches for a user whose name is literally that odd string, and no such user exists, so it matches nothing and returns no rows. Against a query built by concatenation the same string would have altered the query's condition to be always true and returned every row, but the parameter boundary keeps it as a literal value, and the table's rows remain intact.

  1. Why must the fix be applied to every query, and what special cases require attention?

Because a single query anywhere in the application built by concatenating input is a vulnerability, so parameterisation must be uniform. Stored procedures require attention because a procedure that builds query text from input internally is injectable inside the procedure and must itself use parameters; object-relational mappers parameterise automatically but their raw-query escape hatch must not be used with concatenated input; and an identifier such as a table or column name from input cannot be a parameter and must be handled with an allow-list.

munotes.in452

Prevention: the Parameterised Query

  1. How is an identifier, such as a column name chosen by input, handled safely?

By mapping the input to an allow-list of permitted identifiers, accepting only one of a fixed set of known-valid names and rejecting anything else, rather than concatenating the input into the query text. Parameters carry values, not identifiers, so a column or table name selected by input cannot be parameterised, and the allow-list ensures the identifier used is always one the application controls, never one built from untrusted input.

Contents This chapter on its own page

munotes.in453

Chapter Ninety-Eight

Defence in Depth: Least Privilege, Validation and the Web Application Firewall

Syllabus topic Module 2, "SQL Injection - Attack Logic and Prevention: ... database vulnerabilities, and secure coding practices"

In one line

Parameterised queries remove SQL injection; these layers limit the damage if one query is ever missed: a least-privilege database account so a missed query cannot destroy the database, input validation as a supporting layer, safe stored procedures, no leaked errors, and a web application firewall as an outer net that is never the fix.

In examination wording: defence in depth against SQL injection supplements the primary control, parameterised queries, with a database account restricted to the minimum privileges the application requires, input validation, correctly written stored procedures, suppression of database errors, and a web application firewall; these limit the impact of any residual injection but do not replace the primary fix.

The ordering, which is the point

The previous chapter gave the definitive fix: parameterise every query. This chapter adds layers that limit the damage if one query is missed, and the ordering matters as much as the content, because the common mistake is to reach for these layers instead of the fix.

The rule: parameterise every query (the fix), then apply these layers (the net). A web application firewall in front of injectable code is a delay, not a cure; input validation supports but does not prevent injection; a least-privilege account limits damage but does not stop the attack. Each is valuable as defence in depth and dangerous as a substitute, and a student and an assessor must state which is which.

Least-privilege database account

The most valuable of the layers, because it limits what a missed injection can do.

An application connects to its database using a database account, and that account has privileges: what it may read, write, and do. The common mistake is to give the application a powerful account (one that can read any table, drop tables, or perform administrative operations) because it is easy. The consequence is that a single SQL injection anywhere gives the attacker all of those privileges: if the account can drop tables, the injection can drop tables; if it can read every table, the injection can read every table.

Least privilege on the database account limits this: the application's account is granted only what the application actually needs, usually read and write on specific tables, and never the ability to drop tables, read the whole system, or perform administrative operations. Then, even if a query is missed and an injection succeeds, the attacker is confined to what the account can do, which should be little. This does not prevent the injection, but it turns a catastrophe (the whole database read and destroyed) into a contained incident, which is exactly the least-privilege principle from the system-hacking block applied to the database.

A refinement: different parts of an application can use different accounts with different privileges, so a public-facing feature's account can be more restricted than an administrative one, limiting what an injection in each can reach.

munotes.in454

Defence in Depth: Least Privilege, Validation and the Web Application Firewall

Input validation

The supporting layer, whose precise role the input-validation chapter established and this chapter reaffirms for SQL specifically.

Input validation (checking that input is the expected type, length, format and range) reduces the attack surface: much malformed injection-shaped input never reaches the query because it fails validation. But it is not the fix, for the reasons the input-validation chapter gave: valid-looking input can still be crafted to inject, and legitimate input contains characters significant to SQL. So validation supports the parameterised query; it does not replace it.

The correct posture: validate input for shape (a supporting layer), and parameterise every query (the fix). A developer who validates and does not parameterise is filtering, which is fragile; a developer who parameterises is safe regardless, and validation makes the surface smaller.

Safe stored procedures

Stored procedures are sometimes recommended as an injection defence, and the truth is more precise. A stored procedure is safe only if it uses parameters internally; a procedure that builds query text from input inside itself is injectable, and the injection has simply moved into the procedure. So stored procedures are not a defence in themselves; a correctly written stored procedure that parameterises is, and it is equivalent to a parameterised query. The block's rule holds: the defence is the parameter boundary, wherever the query is built.

Suppressing database errors

The error-based-injection chapter established this: generic error pages for users, detailed errors to server-side logs. For SQL injection specifically, suppressing database errors removes the error-based extraction channel and hides the database structure, which supports the defence. It does not fix the injection (parameterised queries do), and blind injection shows hiding output cannot suffice, but it removes one channel and the structural disclosure, which is worthwhile defence in depth.

The web application firewall

An outer net, and the layer most often mistaken for a fix, so the chapter is precise about it.

A web application firewall (WAF) sits in front of the application and inspects requests, blocking those that match patterns of known attacks, including SQL injection patterns. Its value:

  • It can block known injection patterns before they reach the application, catching some attacks and some automated tools.
  • It provides a quick, temporary mitigation when a vulnerability is discovered and cannot be fixed in the code immediately, buying time.
  • It offers monitoring, alerting on injection attempts.

Its limit, and the reason it is never the fix:

  • It works by pattern-matching, so it can be bypassed by injection that does not match its patterns (encodings, novel forms), the recurring filtering-is-fragile lesson at the perimeter.
  • A WAF in front of injectable code is a delay, not a cure: the vulnerability is still there, and a determined attacker gets past the patterns. Relying on a WAF and not fixing the code is the mistake.
munotes.in455

Defence in Depth: Least Privilege, Validation and the Web Application Firewall

So the WAF is defence in depth: valuable as an outer net and a temporary mitigation, never a substitute for parameterised queries. An assessor who finds an application relying on a WAF instead of parameterising its queries reports that the underlying vulnerability is unfixed.

The layered defence, ordered

  1. Parameterise every query (and use allow-lists for identifiers): the fix, removing the injection.
  2. Least-privilege database account: limits what a missed injection can do; the most valuable net.
  3. Input validation for shape: reduces surface; supporting, not the fix.
  4. Correctly-written stored procedures (parameterised) where used.
  5. Suppress database errors: removes the error channel and structural disclosure.
  6. Web application firewall: an outer net and temporary mitigation; never the fix.

A site with the fix and these nets has removed the injection and limited the damage of any that slips through, which is the layered posture the book recommends throughout.

A worked example, framed defensively

An assessor reviews an application's SQL injection defences.

  • Queries are parameterised after the previous chapter's fixes. Good: the injection is removed.
  • The application's database account can drop tables and read every table. Finding: a missed query would be catastrophic. Fix: least privilege, granting only read and write on the needed tables.
  • Input validation is relied upon in one legacy area instead of parameterisation. Finding: validation is not the fix; parameterise there too.
  • Database errors are shown to users. Finding: error channel and structural disclosure; generic errors, detail to logs.
  • A WAF is deployed, and the client believed it made the application safe. Finding, and an important correction: the WAF is an outer net, bypassable, and the underlying code must be fixed; do not rely on it.

The report's ordering is the chapter's: parameterise everything (the fix), then least privilege, validation, safe procedures, error suppression, and the WAF as a net. The correction the client most needs is that the WAF is not a fix, which is the common mistake this chapter exists to prevent.

What beginners get wrong

  • Reaching for these layers instead of the fix. Parameterised queries are the fix; these limit damage if one is missed. Relying on them instead leaves the injection.
  • Giving the application a powerful database account. A missed injection then gets all its privileges; least privilege confines it, turning a catastrophe into a contained incident.
  • Relying on input validation to prevent injection. It supports the fix by reducing surface; parameterise as well.
  • Thinking stored procedures are inherently safe. Only if they parameterise internally; a procedure building query text from input is injectable.
  • Believing a WAF fixes injection. It is pattern-matching, bypassable, and an outer net; a WAF in front of injectable code is a delay, not a cure. Fix the code.
  • Not suppressing database errors. They provide an extraction channel and disclose structure; generic errors, detail to logs.
munotes.in456

Defence in Depth: Least Privilege, Validation and the Web Application Firewall

Quick revision

  • Order: parameterise every query (the fix), then the nets. Reaching for the nets instead of the fix is the mistake.
  • Least-privilege database account (the most valuable net): grant only what the application needs, never drop-tables or read-everything, so a missed injection is confined; use different accounts for different privilege levels.
  • Input validation: reduces surface; supporting, not the fix.
  • Stored procedures: safe only if they parameterise internally; otherwise injectable.
  • Suppress database errors: generic pages for users, detail to logs; removes the error channel and structural disclosure.
  • Web application firewall: blocks known patterns, a temporary mitigation and monitor, bypassable and never the fix; a WAF in front of injectable code is a delay, not a cure.

Test yourself

  1. Why is the ordering of the defences the central point of this chapter?

Because parameterised queries are the fix that removes SQL injection, and the other measures only limit the damage if a query is missed, so they must supplement the fix rather than replace it. The common and dangerous mistake is to reach for these layers, especially a web application firewall, instead of parameterising, which leaves the vulnerability in place; stating which measure is the fix and which is the net is what prevents that mistake.

  1. How does a least-privilege database account limit the impact of SQL injection?

By granting the application's database account only the privileges it actually needs, usually read and write on specific tables and never the ability to drop tables, read the whole system, or perform administrative operations. Then, even if an injection succeeds through a missed query, the attacker is confined to what that account can do, so the whole database cannot be read or destroyed, turning a potential catastrophe into a contained incident.

  1. What is the precise role of input validation in defending against SQL injection?

It is a supporting layer that reduces attack surface by rejecting malformed injection-shaped input before it reaches the query, but it is not the fix, because valid-looking input can still be crafted to inject and legitimate input contains characters significant to SQL. The correct posture is to validate input for shape as support and to parameterise every query as the actual fix, which works regardless of the input's content.

  1. Are stored procedures a defence against SQL injection?
munotes.in457

Defence in Depth: Least Privilege, Validation and the Web Application Firewall

Only if they are written to use parameters internally; a stored procedure that builds query text from input inside itself is injectable, and the injection has merely moved into the procedure. A correctly written, parameterising stored procedure is safe and equivalent to a parameterised query, so the defence is the parameter boundary wherever the query is built, not the use of a stored procedure as such.

  1. Why is a web application firewall never a substitute for fixing the code?

Because it works by matching requests against patterns of known attacks, so it can be bypassed by injection that does not match its patterns, using encodings or novel forms, and the underlying vulnerability remains in the code behind it. It is valuable as an outer net that blocks known patterns, provides monitoring, and offers a temporary mitigation while a fix is prepared, but a firewall in front of injectable code is a delay rather than a cure, so the code must still be parameterised.

Contents This chapter on its own page

munotes.in458

Chapter Ninety-Nine

Memory Layout: the Stack, the Heap and the Frame

Syllabus topic Module 2, "Buffer Overflow and Memory Exploitation Concepts: Study ... memory layout"

In one line

A running program organises memory into regions: the stack for the short-lived data of function calls, the heap for data that lives longer, and, within the stack, a frame for each function call that holds its local data next to the information needed to return. Understanding this layout is what makes the buffer overflow's danger comprehensible.

In examination wording: a process organises its memory into regions including the stack, which stores function call frames in a last-in-first-out manner, and the heap, which stores dynamically allocated data; each function call creates a stack frame containing its local variables and control information such as the return address, and the adjacency of these within the frame is what gives memory-corruption bugs their security significance.

Why a security topic needs a memory model

The attacks earlier in this book abused logic: a query, a session, a permission, an access-control check. This block abuses the machine underneath the logic, and to understand it a student needs a simple model of how a program uses memory. The chapter builds only that model, at concept level, because without it the next chapter's overflow is a mystery and the defences are arbitrary; with it, both are obvious.

The reason memory safety is a security issue at all: in languages that let the programmer manage memory directly (notably C and C++), the program is responsible for not writing past the space it allocated, and nothing automatically stops it if it does. When a program gets that wrong on data an attacker controls, the attacker can reach beyond the intended space into the program's own control information. So the layout, and specifically what sits next to what, is where the security significance lies.

The regions of memory

A running program's memory is divided into regions, each for a different kind of data. The two that matter here:

The stack. Used for the short-lived data of function calls: the local variables of the function currently running, and the bookkeeping needed to return to whoever called it. It is called a stack because it works last-in-first-out: when a function is called, a new block is added on top; when it returns, that block is removed. This makes it fast and automatic, and it is where the buffer overflow of the next chapter occurs.

The heap. Used for data that must live longer than a single function call, or whose size is not known in advance: data the program explicitly allocates while running and frees when done. It is managed differently from the stack, and it has its own kind of corruption bug (the heap overflow, mentioned in a later chapter).

Other regions hold the program's own code and its global data, but the stack and the heap are where the memory-corruption attacks live, and the stack is the classic case.

munotes.in459

Memory Layout: the Stack, the Heap and the Frame

The stack frame

When a program calls a function, it sets aside a block of stack memory for that call, called a stack frame (or activation record). The frame holds the data that call needs, and its contents are the crux of the whole block:

  • the function's local variables, including any buffers (fixed-size areas for data such as a string or an array);
  • saved control information needed to return correctly, most importantly the return address: the location in the calling code to jump back to when this function finishes.

The single most important fact, and the reason the buffer overflow is dangerous, is that these sit next to each other in the frame. A local buffer and the saved return address are neighbours in memory. The exact arrangement varies, but the essential point holds: a buffer's memory is adjacent to control information, including the return address.

So writing past the end of a buffer does not write into empty space; it writes into the neighbouring memory, which can include the saved control information. That adjacency is what turns a memory mistake into a security problem, and it is the fact the next chapter builds on.

A picture of one frame

A simplified view of a single frame, from the buffer outward toward the caller, is worth holding as a mental image:

Region in the frameHolds
the bufferthe function's local fixed-size array
other saved local stateother saved registers or values
the saved return addresswhere to continue when the function returns
the caller's framethe calling function's data, further along

The direction matters: writing more into "the buffer" than it can hold flows into "other saved local state" and then toward "the saved return address". This is the geography the buffer overflow exploits, and it is why the next chapter can say that overflowing a buffer writes toward the return address.

The stack's discipline, and why overflow breaks it

The stack works because of a strict discipline: each function's frame is added on entry and removed on return, and the return address in each frame tells the program where to go when the function finishes. When a function returns, the program reads the return address from the current frame and jumps there, continuing the caller's work.

That discipline depends on the return address being correct. If the return address in a frame is overwritten, the program, on returning, jumps to wherever the overwritten address now points, not to the caller. The next chapter explains how a buffer overflow can overwrite it and why that is dangerous; this chapter's contribution is the model that makes it clear: the return address is a piece of data in the frame, adjacent to a buffer, that controls where the program goes next.

munotes.in460

Memory Layout: the Stack, the Heap and the Frame

A worked example, at concept level

Consider a function that copies some data into a local buffer, then returns to its caller.

  • On entry, a frame is created for the function, containing the buffer and, beyond it, the saved return address pointing back to the caller.
  • The function fills the buffer with data. If the data fits, all is well: the buffer holds the data, the return address is untouched, and on return the program jumps back to the caller correctly.
  • If the data is larger than the buffer and the function does not check, the copy writes past the buffer's end, into the adjacent saved state and toward the return address. The return address may be overwritten.
  • On return, the program reads the (now possibly overwritten) return address and jumps there. If it was overwritten with nonsense, the program jumps to a nonsense location and crashes; the next chapter explains what happens when the overwriting is controlled.

At this concept level the point is complete: the buffer and the return address are neighbours, so overflowing the buffer can corrupt the return address, which controls where the program goes. Nothing here is an exploit; it is the memory model that makes the security problem comprehensible, which is what MU's "Concepts" asks for.

What beginners get wrong

  • Thinking memory layout is irrelevant to security. The adjacency of a buffer and the return address in a stack frame is precisely what gives buffer overflows their significance; without the layout the attack is inexplicable.
  • Confusing the stack and the heap. The stack holds short-lived call frames last-in-first-out; the heap holds longer-lived, explicitly-allocated data. Each has its own corruption bug.
  • Missing that the return address is data. It is a value stored in the frame, adjacent to buffers, that determines where the program goes on return, which is why overwriting it matters.
  • Assuming writing past a buffer hits empty space. It writes into neighbouring memory, which can include control information such as the return address.
  • Thinking this applies to every language. It is specific to languages that let the program manage memory directly and do not check bounds automatically; memory-safe languages prevent it, as a later chapter explains.

Quick revision

  • A program's memory has regions: the stack (short-lived function-call data, last-in-first-out) and the heap (longer-lived, explicitly-allocated data), plus code and globals.
  • Each function call creates a stack frame holding the call's local variables (including buffers) and saved control information, notably the return address (where to go on return).
  • The crucial fact: within the frame, a buffer is adjacent to the return address, so writing past the end of a buffer writes into neighbouring memory and toward the return address.
  • The stack's discipline depends on the return address being correct; overwriting it redirects where the program goes on return, which the next chapter develops.
  • This is specific to languages that manage memory directly without automatic bounds checking.
munotes.in461

Memory Layout: the Stack, the Heap and the Frame

Test yourself

  1. What are the stack and the heap, and what kind of data does each hold?

The stack holds the short-lived data of function calls, the local variables and control information of the currently running functions, organised last-in-first-out so a frame is added on call and removed on return. The heap holds data that must live longer than a single function call or whose size is not known in advance, allocated explicitly while the program runs and freed when done. The stack is where the classic buffer overflow occurs.

  1. What does a stack frame contain, and which adjacency gives it security significance?

A stack frame contains the function call's local variables, including any fixed-size buffers, and saved control information needed to return correctly, most importantly the return address, which is where the program continues when the function finishes. Its security significance comes from the adjacency of the buffer and the return address within the frame: writing past the end of a buffer writes into neighbouring memory and toward the return address.

  1. Why is the return address described as "data in the frame that controls where the program goes"?

Because it is a value stored in the stack frame, alongside the local variables, that the program reads when the function returns in order to jump back to the caller and continue. Since it determines the location the program jumps to on return, and it sits adjacent to buffers that a function writes into, corrupting it by writing past a buffer changes where the program goes, which is the basis of the buffer-overflow attack.

  1. Why does writing past the end of a buffer not simply hit empty space?

Because a buffer is part of a stack frame in which local variables and control information sit next to one another, so the memory immediately beyond a buffer belongs to other saved state and, further along, the saved return address. Writing more into the buffer than it holds therefore flows into that neighbouring memory rather than into unused space, which can corrupt the control information.

  1. Why is this memory model specific to certain languages?

Because the buffer overflow depends on a language that lets the programmer manage memory directly and does not automatically check that data fits the space allocated for it, as C and C++ do not. In memory-safe languages, which check bounds automatically or prevent the mistake by design, writing past a buffer raises an error rather than corrupting adjacent memory, so the layout does not have the same security significance.

Contents This chapter on its own page

munotes.in462

Chapter One Hundred

Stack-Based Buffer Overflow and Return-Address Overwriting

Syllabus topic Module 2, "Buffer Overflow and Memory Exploitation Concepts: Study stack-based buffer overflow ... return address overwriting"

In one line

A stack-based buffer overflow writes more data into a fixed-size buffer than it holds, so the excess corrupts the neighbouring memory, which can include the saved return address. If the overflowing data is attacker-controlled, the return address can be overwritten, so the program, on returning, jumps where the attacker chose rather than back to the caller.

In examination wording: a stack-based buffer overflow occurs when a program writes data beyond the bounds of a fixed-size buffer on the stack, corrupting adjacent memory including the saved return address; where the written data is controlled by an attacker, the return address can be replaced, so that on function return execution transfers to an address of the attacker's choosing, potentially leading to arbitrary code execution.

Building on the memory model

The previous chapter established the model this chapter needs: a stack frame holds a function's local buffer adjacent to the saved return address, and writing past the end of the buffer writes toward the return address. This chapter states what follows, at concept level.

The vulnerability is simple to state: a function copies data into a fixed-size buffer without checking that the data fits. If the data is larger than the buffer, the copy keeps writing past the buffer's end, over the neighbouring saved state, and into the saved return address.

Why the overflow is dangerous: overwriting the return address

Consider what the corrupted return address does. When the function finishes, the program reads the return address from the frame and jumps there to continue. Two cases follow, and the distinction is the whole chapter:

If the overwriting data is random or uncontrolled, the return address becomes a nonsense value, so the program jumps to a nonsense location and crashes. That crash is itself significant: it is a denial of service (the program stops), and it is a sign of a memory-safety bug, which is why a reproducible crash from over-long input is a finding worth reporting, not something to dismiss.

If the overwriting data is attacker-controlled, the attacker can choose what value overwrites the return address, and therefore choose where the program jumps. This is return-address overwriting, and it is what turns a memory mistake into a way to redirect execution. Instead of returning to the caller, the program continues at an address the attacker specified.

That is the essence, and it is where the concept-level treatment stops: control of the return address means control of where execution goes. The techniques for arranging useful code to run at the chosen address are exactly what this chapter does not cover; the examinable and defensively-relevant point is the principle: an unchecked write into a buffer can let attacker-controlled input redirect the program.

munotes.in463

Stack-Based Buffer Overflow and Return-Address Overwriting

Why this is so severe

Redirecting execution is the most severe outcome in security, more severe than the data attacks of the earlier blocks, because it can amount to arbitrary code execution: the program can be made to do what the attacker wants, with the program's own privileges. From there an attacker can reach whatever the program could, which on a server can mean full compromise.

This severity, combined with the ubiquity of software written in memory-unmanaged languages, is why so much effort went into the defences of the next chapter, and why memory safety is treated as a first-order security property. Foundational software, operating systems, network services, runtimes, is often written in C or C++, so a memory-safety flaw in it is a flaw in the foundation many other things stand on.

Why the flaw occurs

The flaw is a missing bounds check: the program writes data into a buffer without first confirming the data fits. In languages that manage memory directly, this check is the programmer's responsibility, and nothing automatic prevents the write if the check is omitted. The classic cause is using an operation that copies data into a buffer trusting the data's length rather than limiting it to the buffer's size, so over-long input overflows.

This connects to the input-validation thread: it is another case of trusting input (here, trusting that input is no longer than expected) placed where it does damage (here, a fixed-size buffer). The root is the book's recurring one: untrusted input handled unsafely.

A worked example, at concept level

A network service reads a message from the network into a fixed-size buffer on the stack, using a copy that does not limit the length to the buffer's size.

  • If a message fits the buffer, the service works normally: the message is read, the buffer holds it, the return address is untouched, and the function returns correctly.
  • If a message is longer than the buffer, the copy writes past the buffer's end, over the neighbouring saved state, and into the saved return address.
  • If the over-long message is arbitrary (an accident, or a probe), the return address becomes nonsense and the service crashes: a denial of service, and a clear sign of the bug.
  • If the over-long message is attacker-controlled, the attacker can overwrite the return address with a chosen value, so that when the function returns, execution goes where the attacker directed rather than back into the service.

The finding, stated defensively, is that the service copies network input into a fixed-size buffer without a bounds check, so over-long input corrupts the return address, risking at least a crash and at worst redirection of execution. The fix, in the code, is to use a length-limited copy that never writes more than the buffer holds, and to reject over-long messages, which the next chapter generalises. The example demonstrates none of this by exploitation; it reasons about the code, which is the concept-level, defensive treatment.

munotes.in464

Stack-Based Buffer Overflow and Return-Address Overwriting

What beginners get wrong

  • Thinking a buffer overflow only crashes the program. A crash is the mild, uncontrolled outcome; with attacker-controlled input the return address can be overwritten to redirect execution, which is the severe outcome. Both start from the same unchecked write.
  • Dismissing a crash from over-long input. A reproducible crash is a denial of service and a sign of a memory-safety bug, often a security one; it should be reported, not dismissed.
  • Missing why the return address matters. It controls where the program goes on return, and it is adjacent to the buffer, so overwriting it redirects execution.
  • Believing the flaw is exotic. It is a missing bounds check, an ordinary omission, and it is another case of trusting input (that it is no longer than expected) placed where it does damage.
  • Underrating the severity. Redirecting execution can amount to arbitrary code execution with the program's privileges, the most severe outcome, especially in the foundational software often written in memory-unmanaged languages.
  • Expecting the exploitation detail. The concept is that control of the return address means control of execution; arranging code to run is beyond the concept level and beyond what a defender needs.

Quick revision

  • A stack-based buffer overflow writes past a fixed-size buffer, corrupting adjacent memory including the saved return address, because a function copies data into the buffer without checking it fits (a missing bounds check).
  • On return, the program jumps to the return address. If overwritten with random data, the program crashes (a denial of service and a sign of the bug); if overwritten with attacker-controlled data, execution goes where the attacker chose: return-address overwriting.
  • The principle (concept level): control of the return address means control of where execution goes, potentially arbitrary code execution with the program's privileges, the most severe outcome.
  • It is another case of trusting input (that it is no longer than expected) handled unsafely; the root is the book's recurring one. The fix is in the code (bounds checking) and the protections, both in the next chapter.

Test yourself

  1. Explain a stack-based buffer overflow and why it can be more than a crash.

It occurs when a function copies data into a fixed-size buffer on the stack without checking that the data fits, so over-long data is written past the buffer's end into neighbouring memory, which can include the saved return address. It can be more than a crash because, when the overwriting data is controlled by an attacker, the return address can be replaced with a chosen value, so that on return the program jumps where the attacker directed rather than back to the caller, redirecting execution.

munotes.in465

Stack-Based Buffer Overflow and Return-Address Overwriting

  1. What is return-address overwriting, and what does it achieve at concept level?

It is the overwriting of a function's saved return address by an overflow that reaches it, with attacker-controlled data. At concept level it achieves control of where the program goes when the function returns: instead of continuing at the caller, execution transfers to an address the attacker specified. Control of the return address therefore means control of where execution goes, which can lead to arbitrary code execution.

  1. Why is a crash from over-long input a finding rather than something to dismiss?

Because a reproducible crash from over-long input is a denial of service, since the program stops, and it is a sign of a memory-safety bug in which a write exceeded a buffer's bounds. The same unchecked write that causes the crash with random data could, with attacker-controlled data, redirect execution, so the crash indicates a potentially serious vulnerability that should be investigated and reported.

  1. Why is redirecting execution considered the most severe outcome in security?

Because it can amount to arbitrary code execution: the program can be made to do what the attacker wants, running with the program's own privileges, so the attacker gains whatever access the program had, which on a server can mean full compromise. This is more severe than the data attacks of earlier blocks, and it is especially serious because foundational software such as operating systems and network services is often written in memory-unmanaged languages.

  1. What is the underlying cause of a buffer overflow, and how does it relate to the book's recurring theme?

The underlying cause is a missing bounds check: the program writes data into a buffer without first confirming the data fits, typically by using a copy operation that trusts the data's length rather than limiting it to the buffer's size. It relates to the recurring theme because it is another case of trusting input, here trusting that input is no longer than expected, and handling it unsafely, so that untrusted input placed in a fixed-size buffer does damage.

Contents This chapter on its own page

munotes.in466

Chapter One Hundred One

Heap Overflows and Format-String Flaws, Briefly

Syllabus topic Module 2, "Buffer Overflow and Memory Exploitation Concepts"

In one line

Two more memory-safety flaws round out the concepts: a heap overflow corrupts the heap's own bookkeeping rather than a return address, and a format-string flaw arises when user input is used to control how output is formatted. Both are in the same family as the stack overflow and share its defences.

In examination wording: a heap overflow writes beyond a heap-allocated buffer, corrupting adjacent heap data or the heap's management metadata; a format-string vulnerability occurs when untrusted input is passed as the format specification to a formatting function, allowing an attacker to read or write memory; both are memory-safety defects addressed by the same disciplines as the stack overflow.

Why name these

The stack-based buffer overflow is the archetype and deserved the full treatment. But a student should recognise two neighbouring flaws so they are not a surprise, and so the "memory exploitation concepts" MU names are complete. Both are covered briefly and at concept level, because they share the stack overflow's family (memory corruption from unsafe handling) and, crucially, its defences (the next chapter), so understanding the archetype means understanding these with a short explanation.

Heap overflows

The stack overflow corrupted data on the stack, reaching the return address. A heap overflow is the same kind of mistake, writing past a buffer, but the buffer is on the heap (the region for longer-lived, explicitly-allocated data from the memory-layout chapter) rather than the stack.

Because the heap has no return addresses in the way the stack does, a heap overflow corrupts different things:

  • Adjacent heap data: other data allocated nearby, which the overflow overwrites, corrupting the program's information.
  • The heap's management metadata: the heap keeps its own bookkeeping about which blocks are allocated and free, and this bookkeeping sits in memory near the allocated blocks. An overflow that corrupts this metadata can, in the worst case, be leveraged to influence what the program does when it next manages memory, potentially leading, like the stack overflow, toward redirection of execution.

The concept-level point: a heap overflow is the same unchecked-write mistake in a different memory region, corrupting neighbouring data or the heap's own bookkeeping rather than a return address. It is generally harder to exploit than a stack overflow and is still a serious memory-safety flaw. Its fix is the same as the stack overflow's: do not write past the buffer (bounds checking), and the protections of the next chapter.

A related heap flaw worth naming is the use-after-free: using memory after it has been freed, so that the program acts on data that may have been reused for something else. It is a different memory-safety defect (a timing mistake rather than an overflow) but in the same family, and it is addressed by the same discipline of careful memory management and, definitively, by memory-safe languages.

munotes.in467

Heap Overflows and Format-String Flaws, Briefly

Format-string flaws

A different memory-safety flaw, included because it is a classic and because it illustrates the same root cause, trusting input, in a new place.

Some functions format output according to a format specification: a template with placeholders that says how to format the values that follow. The format specification is meant to be written by the programmer, a fixed template. The vulnerability arises when a program uses user input as the format specification instead of as a value to be formatted.

At concept level: if an attacker controls the format specification, they can include placeholders the program did not intend, and those placeholders can be made to read from or write to memory in ways the program never meant, because the formatting function acts on the placeholders it is given. This can disclose memory contents (reading) or, in the worst case, corrupt memory (writing), leading toward the same kinds of outcome as the overflows.

The fix is simple and is the concept to carry: never use untrusted input as the format specification. The input should be a value that is formatted by a fixed, programmer-written template, not the template itself. This is, once again, the input-trust principle: input must be treated as data (a value to format), not as control (the format specification).

The common thread

All three flaws in this block, the stack overflow, the heap overflow, and the format-string flaw, plus the use-after-free, share a root and a family:

  • The root is unsafe handling of memory or input in a language that does not check it automatically: writing past a buffer, corrupting heap metadata, or letting input control formatting.
  • The family is memory-safety defects, whose worst outcomes tend toward the same place: disclosure of memory, corruption of memory, and potentially redirection of execution.
  • The defences are shared and are the next chapter's subject: not making the mistake (bounds checking, safe input handling), memory-safe languages that prevent the class, and the operating-system and compiler protections that limit the impact.

So a student who understands the stack overflow and this brief chapter understands the memory-exploitation concepts as a whole: unsafe memory handling in unmanaged languages, corrupting different things but sharing defences.

A worked example, at concept level

A code review of a program written in a memory-unmanaged language finds three memory-safety issues, reported at concept level.

  • A function writes past a heap-allocated buffer, corrupting adjacent heap data. Heap overflow. Fix: bounds checking, so the write cannot exceed the buffer.
  • The program uses user input as the format specification in an output function. Format-string flaw, which could read or corrupt memory. Fix: use a fixed format template and pass the input as a value to be formatted.
  • The program uses a block of memory after freeing it. Use-after-free. Fix: careful memory management, or a memory-safe language.
munotes.in468

Heap Overflows and Format-String Flaws, Briefly

The report notes that all three are memory-safety defects in the same family as the stack overflow, that their worst outcomes tend toward disclosure or corruption of memory, and that the durable defence for the whole family is a memory-safe language, with bounds checking and safe input handling fixing the specific cases. The review reasons about the code; it demonstrates nothing by exploitation, which is the concept-level, defensive treatment.

What beginners get wrong

  • Thinking only stack overflows matter. Heap overflows, format-string flaws and use-after-free are neighbouring memory-safety defects in the same family, with the same defences.
  • Confusing a heap overflow with a stack overflow. Both are unchecked writes past a buffer, but a heap overflow corrupts adjacent heap data or the heap's bookkeeping rather than a return address.
  • Missing the format-string root cause. It is using untrusted input as the format specification (control) rather than as a value (data); the fix is a fixed template with the input as a value.
  • Overlooking use-after-free. It is a memory-safety defect of timing (using freed memory) rather than an overflow, in the same family, addressed by careful management or a safe language.
  • Not seeing the common thread. All are unsafe memory or input handling in unmanaged languages, sharing defences; the durable fix for the family is a memory-safe language.

Quick revision

  • Heap overflow: writing past a heap buffer (longer-lived, explicitly-allocated data), corrupting adjacent heap data or the heap's management metadata rather than a return address; generally harder to exploit, still serious. Fix: bounds checking and the next chapter's protections.
  • Use-after-free: using memory after it is freed; a timing memory-safety defect in the same family, fixed by careful management or a safe language.
  • Format-string flaw: using untrusted input as the format specification instead of as a value, letting an attacker read or corrupt memory. Fix: never use untrusted input as the format specification; use a fixed template with the input as a value.
  • Common thread: unsafe memory or input handling in unmanaged languages, corrupting different things, sharing defences (bounds checking, safe input handling, memory-safe languages, and the OS/compiler protections of the next chapter).

Test yourself

  1. How does a heap overflow differ from a stack overflow?

Both are the same kind of mistake, writing past the end of a fixed-size buffer, but a heap overflow occurs in a buffer on the heap, the region for longer-lived explicitly-allocated data, rather than on the stack. Because the heap has no return addresses in the way the stack does, a heap overflow corrupts adjacent heap data or the heap's own management metadata rather than a saved return address, and it is generally harder to exploit while remaining a serious memory-safety flaw.

munotes.in469

Heap Overflows and Format-String Flaws, Briefly

  1. What is a format-string vulnerability, and what is its root cause?

It is a flaw in which a program uses untrusted input as the format specification passed to a formatting function, instead of as a value to be formatted, so an attacker who controls the format specification can include placeholders that read from or write to memory in ways the program never intended. Its root cause is the recurring one of trusting input: the input is treated as control, the template, rather than as data, a value, which the fix corrects by using a fixed programmer-written template.

  1. What is the fix for a format-string flaw?

Never to use untrusted input as the format specification. The input should be passed as a value to be formatted by a fixed, programmer-written format template, so that the placeholders and formatting are controlled by the program and the input is treated strictly as data, not as the specification that controls how output is produced.

  1. What is a use-after-free, and to which family does it belong?

A use-after-free is using a block of memory after it has been freed, so the program acts on data that may since have been reused for something else, leading to unpredictable and potentially exploitable behaviour. It is a memory-safety defect of timing rather than an overflow, but it belongs to the same family as the stack and heap overflows and format-string flaws, and it is addressed by careful memory management and, definitively, by memory-safe languages.

  1. What do the flaws in this block have in common, and what is the durable defence for the family?

They are all memory-safety defects arising from unsafe handling of memory or input in languages that do not check it automatically, whether writing past a buffer, corrupting heap metadata, using freed memory, or letting input control formatting, and their worst outcomes tend toward disclosure or corruption of memory and potentially redirection of execution. They share their defences, and the durable defence for the whole family is a memory-safe language that prevents the class, supported by bounds checking, safe input handling, and the operating-system and compiler protections of the next chapter.

Contents This chapter on its own page

munotes.in470

Chapter One Hundred Two

Defences: Bounds Checking, Canaries, DEP, ASLR and Safe Languages

Syllabus topic Module 2, "Buffer Overflow and Memory Exploitation Concepts: ... secure programming techniques"

In one line

The real fix for buffer overflows is not to overflow: bounds checking, and memory-safe languages that check automatically. Then a safety net for mistakes that remain: stack canaries detect the overwrite, a non-executable stack blocks running injected data, and address randomisation removes the predictability an attacker needs. They are used together because none is perfect alone.

In examination wording: buffer overflows are prevented at source by bounds checking and by memory-safe languages that check array bounds automatically; for code where the mistake still occurs, defence in depth is provided by stack canaries, which detect corruption of the return address before it is used, non-executable memory (data execution prevention), which prevents execution of injected data, and address space layout randomisation, which makes the location of code and data unpredictable.

The structure of the defence

The chapter's structure is its argument, so state it first. There are two levels:

  1. The real fix: do not overflow. Bounds checking, and memory-safe languages, which remove the flaw at its source. If the write never exceeds the buffer, there is no overflow, and the whole class is gone.
  2. The safety net: limit the impact of overflows that remain. For existing code in memory-unmanaged languages, where the mistake still occurs, stack canaries, non-executable memory and address randomisation make an overflow far less likely to become a successful redirection of execution.

The ordering matters: the protections are a safety net for mistakes, not a substitute for not making them. A student and a defender should understand that the durable answer is memory safety, and the protections buy safety for the vast body of existing code that is not memory-safe.

The real fix: do not overflow

Bounds checking. The direct fix: before writing data into a buffer, check that it fits, and never use an operation that copies data trusting its length rather than limiting it to the buffer's size. Use length-limited operations, reject over-long input, and confirm sizes. In secure coding, the whole class is avoided by never writing past a buffer, which is the "secure programming technique" MU names. It is the programmer's responsibility in memory-unmanaged languages, and it is where the flaw is truly fixed.

Memory-safe languages. The more powerful and increasingly-preferred fix: languages that check array bounds automatically (or prevent the mistake by design), so that an attempt to write past a buffer raises an error rather than corrupting memory. Languages like Python, Java, Go and Rust remove this entire class of flaw, because the unsafe write cannot happen. This is why much of the software world has moved away from manual memory management for new code, and why memory-safe languages are the durable answer: they make the mistake impossible rather than relying on the programmer to avoid it.

munotes.in471

Defences: Bounds Checking, Canaries, DEP, ASLR and Safe Languages

The concept to carry: the real fix is that the overflow does not happen, by checking bounds or by using a language that checks for you. The protections below matter for code where this is not the case.

The safety net: protections for existing code

For the enormous body of existing C and C++ code, and for new code in those languages, three protections limit the impact of an overflow that occurs. Knowing what each does, and why none suffices alone, is the examinable core.

Stack canaries. The compiler places a known secret value, a canary, between the buffer and the saved return address. Before the function returns, it checks the canary is intact. An overflow that reached the return address must have overwritten the canary on the way (since the canary sits between the buffer and the return address), so the check detects the tampering and the program aborts instead of returning to the attacker's address. The canary turns a silent redirection into a detected, controlled abort. Its limit: it detects the classic sequential overflow to the return address, but does not stop every memory-corruption technique.

Non-executable memory (data execution prevention, DEP). The operating system marks regions that hold data, such as the stack, as not executable, so the processor refuses to run instructions from them. This means that even if an attacker redirects execution into data they placed on the stack, the processor will not execute it, because that region is data-only. Its limit: it stops running injected data, but does not stop techniques that redirect execution to existing legitimate code rather than to injected data.

Address space layout randomisation (ASLR). The operating system loads the program's parts at random addresses each time it runs, so the attacker cannot reliably predict where anything is. Since redirecting execution usefully requires knowing where to redirect it to, randomising the layout makes exploitation much harder and less reliable, because the attacker cannot know the address to use. Its limit: it raises the difficulty rather than removing the possibility, and it can be weakened if an information-disclosure flaw reveals an address.

Why they are used together

The examinable point about the safety net: none of the protections is perfect alone, so they are used together, and each closes a gap the others leave.

  • A canary detects the classic overwrite, but not every corruption technique.
  • A non-executable stack blocks running injected data, but not redirection to existing code.
  • ASLR removes predictability, but can be undermined by an information disclosure.

Layered, they are strong: an attacker must defeat the canary, and avoid needing to run injected data, and defeat the randomisation, all at once, which is far harder than defeating any one. This is defence in depth applied to memory safety, and it is why modern systems enable all three. But the honest summary, and the one to carry, is that they make exploitation harder and less reliable, not impossible, which is exactly why the real fix, memory safety, matters: the protections buy safety for unsafe code, while memory-safe languages remove the flaw.

munotes.in472

Defences: Bounds Checking, Canaries, DEP, ASLR and Safe Languages

A worked example, framed defensively

A code review and configuration assessment examines a network service written in C, reporting at concept level.

  • A function copies network input into a fixed-size buffer using a copy that does not limit length. The flaw: an unchecked write, risking a crash or redirection (the previous chapters). The real fix: use a length-limited copy and reject over-long input (bounds checking).
  • The build enables stack canaries, the operating system enforces a non-executable stack and ASLR. Recorded as defence in depth: an overlooked overflow is far less likely to become code execution, though these are a net, not a fix.
  • The organisation writes new components in a memory-safe language. Recorded as the durable answer: new code cannot have this class of flaw.

The report's structure is the chapter's: the real fix is not to overflow (bounds checking, and memory-safe languages for new code), and the canary, non-executable memory and ASLR are the safety net for the existing C code, used together because none is perfect alone. The assessment reasons about the code and the build configuration; it demonstrates nothing by exploitation.

What beginners get wrong

  • Thinking the protections make bounds checking unnecessary. Canaries, non-executable memory and ASLR make exploitation harder, but the real fix is not to overflow; they are a safety net for mistakes.
  • Believing any one protection is sufficient. Each has a limit: canaries miss some techniques, non-executable memory does not stop redirection to existing code, ASLR can be undermined by a disclosure. They are used together.
  • Assuming memory-safe languages have no security bugs at all. They remove the memory-safety class, but can still have logic flaws, injection, broken access control and the rest. They fix memory safety, not security in general.
  • Dismissing bounds checking as obvious. It is the direct fix and is still omitted; using length-limited operations and rejecting over-long input is the secure-programming technique that prevents the flaw.
  • Overrating the protections' completeness. They make exploitation harder and less reliable, not impossible; the durable answer is memory safety.
  • Expecting exploitation detail. The defensive point is what each protection does and why they are layered, not how they are bypassed.

Quick revision

  • The real fix: do not overflow. Bounds checking (check data fits, use length-limited operations, reject over-long input) and memory-safe languages (Python, Java, Go, Rust) that check automatically, removing the class. The durable answer.
  • The safety net for existing/unmanaged code, used together:
  • Stack canaries: a secret value between buffer and return address; checked before return, so an overflow that reached the return address is detected and the program aborts. Misses some techniques.
  • Non-executable memory (DEP): data regions like the stack are marked non-executable, so injected data cannot run. Does not stop redirection to existing code.
  • ASLR: program parts loaded at random addresses, so the attacker cannot predict where to redirect. Can be undermined by an information disclosure.
  • None is perfect alone, so all are used together; they make exploitation harder and less reliable, not impossible, which is why memory safety is the real fix. Memory-safe languages fix memory safety, not security in general.
munotes.in473

Defences: Bounds Checking, Canaries, DEP, ASLR and Safe Languages

Test yourself

  1. What is the real fix for buffer overflows, and how do the other protections relate to it?

The real fix is that the overflow does not happen: bounds checking, so a write never exceeds the buffer, and memory-safe languages that check array bounds automatically so the unsafe write cannot occur, removing the entire class. The other protections, stack canaries, non-executable memory and address randomisation, are a safety net that limits the impact of overflows in code where the mistake still occurs, not a substitute for preventing them.

  1. How does a stack canary work, and what is its limit?

The compiler places a known secret value, the canary, between the buffer and the saved return address, and checks that it is intact before the function returns. Because an overflow reaching the return address must overwrite the canary on the way, the check detects the tampering and the program aborts instead of returning to the attacker's address. Its limit is that it detects the classic sequential overflow to the return address but does not stop every memory-corruption technique.

  1. What does a non-executable stack prevent, and what does it not stop?

It causes the operating system to mark data regions such as the stack as non-executable, so the processor refuses to run instructions from them, which prevents execution of data an attacker placed on the stack even if execution is redirected there. It does not stop techniques that redirect execution to existing legitimate code rather than to injected data, since that code is in an executable region.

  1. How does address space layout randomisation make exploitation harder, and how can it be weakened?

It loads the program's parts at random addresses each time it runs, so the attacker cannot reliably predict where code or data is located, and since redirecting execution usefully requires knowing the target address, the randomisation makes exploitation much harder and less reliable. It can be weakened if an information-disclosure flaw reveals an actual address, giving the attacker the location the randomisation was hiding.

munotes.in474

Defences: Bounds Checking, Canaries, DEP, ASLR and Safe Languages

  1. Why are the protections used together, and what does that imply about the importance of memory safety?

Because none is perfect alone: canaries miss some corruption techniques, non-executable memory does not stop redirection to existing code, and ASLR can be undermined by an information disclosure, so layering them forces an attacker to defeat all three at once, which is far harder. That they make exploitation only harder and less reliable, not impossible, implies that the real fix remains memory safety, bounds checking and memory-safe languages, which remove the flaw rather than mitigating its impact.

Contents This chapter on its own page

munotes.in475

Chapter One Hundred Three

How Wi-Fi Works: Frames, SSIDs and Association

Syllabus topic Module 2, "Wireless Network Security and Authentication Mechanisms: Compare WEP, WPA, WPA2, WPA3 protocols, wireless sniffing risks, rogue access points, and wireless security best practices"

In one line

Wi-Fi sends data through the air, where anyone in range receives it, so it must be encrypted; that is the fact the whole block turns on. Devices find and join a network by its SSID through association, and hiding the SSID is not security.

In examination wording: wireless networking transmits data as radio frames that any device within range can receive, so confidentiality depends on link-layer encryption; a network is identified by its SSID, which access points advertise in beacon frames, and devices join through an association process; concealing the SSID does not provide security because the network's presence and name are still discoverable.

The fact that governs the block

A wired network has a physical boundary: to read the traffic you must reach the cable, which the sniffing block showed requires defeating a switch. Wi-Fi has no such boundary. The signal is radio, broadcast through the air, and it passes through walls and out into the street, so anyone within range receives every frame, with no need to defeat any switch or tap any cable. Receiving the signal is passive and undetectable.

This single fact governs the entire wireless block, and a student should hold it as the reason for everything that follows: because anyone in range receives the frames, encryption of the link is not optional; it is the only thing standing between your traffic and anyone with an antenna. The history of Wi-Fi security, which the next chapters trace, is the history of getting that encryption right, and it took four generations, which is why MU asks you to compare them.

The sniffing block's conclusion applies directly and more forcefully here: on Wi-Fi, capturing the traffic requires no trick at all, so the durable defence is that the traffic, once captured, reveals nothing, which is encryption.

Frames, SSIDs and beacons

A little vocabulary, because the attacks use it.

Frames. Wireless data travels in frames, the wireless equivalent of the frames from the sniffing block. There are frames carrying data, and management frames that run the network: announcing its presence, joining it, and leaving it. The management frames matter for the attacks, because some of them are, in the older standards, unauthenticated (the deauthentication attack of a later chapter).

SSID. A wireless network is identified by its SSID (Service Set Identifier), its network name, the name you see when choosing a network to join.

Beacon frames. An access point (the device providing the Wi-Fi) periodically broadcasts beacon frames advertising its presence and its SSID, so that devices can discover it. This advertising is how your device shows you the available networks.

Association. To join a network, a device goes through association: it discovers the network (from beacons or by asking), authenticates if required, and associates with the access point, after which it can exchange data. The authentication step is where the security standards of the following chapters do their work.

munotes.in476

How Wi-Fi Works: Frames, SSIDs and Association

Why hiding the SSID is not security

A common belief is that hiding the SSID (configuring the access point not to broadcast its name in beacons) secures the network. It does not, and a student should be able to say why, because it is the wireless instance of the "obscurity is not security" principle from the footprint-audit chapter.

  • The network is still there and still discoverable. The access point still transmits, and its presence is visible; only the name is omitted from the beacon.
  • The name is revealed when a device connects. When a legitimate device joins a hidden network, it must name the network in its request, and that request is broadcast in the air like everything else, so anyone listening learns the name. So the SSID is disclosed by ordinary use.
  • It can inconvenience legitimate users and devices more than attackers, since devices must be configured to look for the hidden network and may probe for it, which itself leaks the name.

So hiding the SSID is, at best, a trivial obstacle and, like all obscurity, an invalid primary control. The real security of a wireless network is its encryption standard (the next chapters) and its authentication, not the concealment of its name. Hiding the SSID may be done as a minor measure, but it must never be relied upon, and treating a hidden SSID as securing a network is a finding.

A worked example, framed defensively

An assessor reviews a wireless network's basic configuration, listening only for the broadcast beacons any device receives (which is passive reception, not an attack on anyone's traffic), on the client's own network with authorisation.

  • The network broadcasts its SSID and is protected by an encryption standard (assessed in the next chapters). Normal.
  • A second network has its SSID hidden, and the client believes this secures it. Finding, and a correction: the network is still discoverable, and its name is revealed whenever a device connects, so hiding the SSID is not security; the encryption standard and authentication are what matter. Recommendation: rely on strong encryption (next chapters), not on hiding the name.
  • The assessor confirms the network's presence from its beacons and notes that receiving beacons is passive; the security assessment focuses on the encryption standard, which the following chapters examine.

The report establishes the governing fact for the client, that Wi-Fi is broadcast so anyone in range receives it, which is why link encryption is essential, and corrects the hidden-SSID misconception. The assessor listens only for broadcast beacons, not others' traffic, which is the ethical way to survey a wireless environment.

munotes.in477

How Wi-Fi Works: Frames, SSIDs and Association

What beginners get wrong

  • Thinking Wi-Fi has a boundary like a wire. It is broadcast radio; anyone in range receives every frame, passively and undetectably, with no trick needed.
  • Underrating why encryption is essential on Wi-Fi. Because capturing the signal is trivial, encryption is the only thing that keeps captured traffic unreadable; it is not optional.
  • Believing hiding the SSID secures a network. The network is still discoverable and the name is revealed when devices connect; it is obscurity, an invalid primary control.
  • Confusing the SSID with security. The SSID is the network's name; security is the encryption standard and authentication, not the name or its concealment.
  • Forgetting management frames. Some, in older standards, are unauthenticated, which enables attacks like deauthentication; the frames are not only data.
  • Treating listening for beacons as an attack. Receiving broadcast beacons is passive; the ethical line, as in the sniffing block, is at capturing others' actual traffic.

Quick revision

  • Wi-Fi is broadcast radio: anyone in range receives every frame, passively and undetectably, with no trick needed. This governs the block: link encryption is not optional, it is the only protection for captured traffic.
  • Vocabulary: frames (data and management frames, some of the latter unauthenticated in older standards), SSID (the network name), beacon frames (advertise the network and SSID), association (discover, authenticate, associate to join).
  • Hiding the SSID is not security: the network is still discoverable and the name is revealed when a device connects; it is obscurity, an invalid primary control. Security is the encryption standard and authentication, the next chapters.

Test yourself

  1. What single fact about Wi-Fi governs the whole wireless block, and what follows from it?

That Wi-Fi is broadcast radio, so anyone within range receives every frame, passively and undetectably, with no need to defeat a switch or tap a cable as on a wired network. It follows that encryption of the wireless link is not optional but essential, because it is the only thing that keeps the easily-captured traffic unreadable, which is why the security of Wi-Fi is a matter of getting the encryption standard right.

  1. What are beacon frames and association?

Beacon frames are management frames that an access point periodically broadcasts to advertise its presence and its SSID, so that devices can discover the available networks. Association is the process by which a device joins a network: it discovers the network, authenticates if required, and associates with the access point, after which it can exchange data; the authentication step is where the wireless security standards operate.

  1. Why does hiding the SSID not secure a network?
munotes.in478

How Wi-Fi Works: Frames, SSIDs and Association

Because the network is still present and discoverable, since the access point still transmits and its presence is visible even without the name in its beacons, and because the name is revealed whenever a legitimate device connects, as the device must name the network in a request that is broadcast in the air for anyone to hear. Hiding the SSID is therefore obscurity rather than security, an invalid primary control, and it can inconvenience legitimate users more than attackers.

  1. What actually secures a wireless network, if not the concealment of its name?

Its encryption standard and its authentication: the link-layer encryption that keeps captured traffic unreadable and the authentication that controls who may join, which are the subject of the following chapters comparing WEP, WPA, WPA2 and WPA3. Concealing the SSID may be a minor supplementary measure but must never be relied upon.

  1. Why is listening for beacon frames not an attack, and where is the ethical line in a wireless survey?

Because beacon frames are broadcast by access points for any device to receive in order to discover networks, so receiving them is passive reception of information openly advertised, not interference with anyone's communications. The ethical line, as in the sniffing block, is at capturing others' actual traffic without authorisation, which is an act under the law; surveying the wireless environment by receiving broadcast beacons stays on the passive side of that line.

Contents This chapter on its own page

munotes.in479

Chapter One Hundred Four

WEP and Why It Broke

Syllabus topic Module 2, "Wireless Network Security and Authentication Mechanisms: Compare WEP, WPA, WPA2, WPA3 protocols"

In one line

WEP was the first Wi-Fi encryption standard, and it is comprehensively broken: a flaw in how it used its cipher lets the key be recovered from captured traffic in minutes. A network on WEP should be treated as having no encryption at all.

In examination wording: Wired Equivalent Privacy was the original wireless encryption standard, using the RC4 stream cipher with a short initialisation vector; weaknesses in its use of the cipher, principally the reuse of initialisation vectors, permit recovery of the key from sufficient captured traffic, so WEP provides no meaningful confidentiality and must not be used.

WEP as the first lesson

The wireless block asks the student to compare four standards, and WEP is where the comparison starts, because it is the clearest lesson in the whole block: encryption can be sound in its cipher and broken in its use. WEP did not use a strange cipher; it used a standard one, RC4, and it used it in a way that undid its protection. This is the cryptographic-weaknesses chapter's thesis, that real failures are sound primitives used wrongly, in its wireless form, and it is why WEP is worth studying even though nobody should use it.

WEP's name, "Wired Equivalent Privacy", stated its aspiration: to give wireless the privacy of a wire. It failed at that comprehensively, and understanding the failure teaches what the later standards had to fix.

How WEP worked, and where it went wrong

WEP encrypted each frame with the RC4 stream cipher, combining the network's shared key with a per-frame value called an initialisation vector (IV) to produce the keystream that encrypts the frame. The idea of an IV is sound and appears throughout cryptography: a value that varies per message so that the same key does not produce the same keystream twice, which the cryptographic-weaknesses chapter noted must be unique.

WEP's fatal mistakes were in the details of this:

  • The initialisation vector was too short. It had too few bits, so on a busy network the IVs repeat after a manageable amount of traffic. When two frames use the same IV with the same key, they use the same keystream, and reusing a keystream is exactly the cryptographic weakness the earlier chapter warned against, because it leaks information relating the two frames.
  • The IV was sent in the clear with each frame, so an attacker capturing traffic sees the IVs and knows when one repeats.
  • The way the key and IV were combined had statistical weaknesses that, given enough frames with repeating IVs, allow the key itself to be recovered by analysis, not merely individual frames to be decrypted.

The consequence: an attacker who passively captures enough WEP traffic (which, as the previous chapter established, requires no trick, only an antenna in range) can recover the network's key through analysis, and once they have the key they can decrypt all traffic and join the network. On a busy network this takes minutes, and it can be accelerated. So WEP does not merely leak individual frames; it surrenders the key.

munotes.in480

WEP and Why It Broke

Why "treat WEP as no encryption"

The practical conclusion, and the one to carry: a network protected only by WEP should be treated as having no encryption at all. The key can be recovered from passively captured traffic in minutes, after which the attacker has full access to the traffic and the network. WEP's protection is not weak, it is effectively absent against anyone who bothers, and its presence gives a false sense of security, which is worse than knowing you are unprotected.

WEP is long deprecated and should never be used or accepted. Finding a network still on WEP is a serious finding, both because the network is effectively unencrypted and because its presence indicates old, unmaintained equipment or configuration.

The lesson for the standards that followed

WEP's failure defined what its successors had to fix, which is why studying it sets up the comparison:

  • The initialisation vector had to be long enough not to repeat, and used correctly.
  • The cipher and its mode had to be sound in use, not just in principle.
  • The key had to be protected so that capturing traffic could not recover it.

WPA was the immediate, transitional response (the next chapter), designed to fix WEP's worst problems on the same hardware; WPA2 replaced the cipher entirely with AES; WPA3 strengthened the handshake. Each step is a response to a weakness the previous standard left, and WEP is the origin of the sequence.

A worked example, framed defensively

An assessor surveys a client's wireless environment, listening for beacons (passive) to identify the standards in use, on the client's own networks with authorisation.

  • One access point advertises WEP. A serious finding: WEP is comprehensively broken, its key recoverable from passively captured traffic in minutes, so the network is effectively unencrypted, and any traffic on it, and access to it, is exposed. Recommendation: replace immediately with WPA2 (AES) at minimum, or WPA3, and replace the equipment if it supports only WEP.
  • The WEP network also suggests old, unmaintained equipment. Recommendation: review the device's other security and its firmware currency.
  • The assessor does not capture and analyse the network's traffic to recover the key, which would be reading the client's communications; the finding that WEP is broken follows from the standard in use, established from the beacon, which is the ethical way to report it.
munotes.in481

WEP and Why It Broke

The report states plainly that WEP provides no meaningful protection and must be replaced, and uses WEP as the illustration of the block's theme: the cipher was standard, the use was wrong, and the result was no security. The assessor establishes the finding from the advertised standard, not by breaking the client's network.

What beginners get wrong

  • Thinking WEP is weak but usable. It is effectively broken: the key is recoverable from passively captured traffic in minutes, so it should be treated as no encryption and never used.
  • Blaming the cipher. RC4 was a standard cipher; WEP failed in how it used it, principally the short, reused initialisation vector, which is the "sound primitive used wrongly" lesson.
  • Missing that WEP surrenders the key. It does not merely leak individual frames; analysis of enough captured frames recovers the key itself, giving full access.
  • Underrating the false-security cost. WEP's presence suggests protection while providing none, which is worse than known exposure.
  • Treating a WEP network as merely a configuration nit. It is effectively unencrypted and usually indicates old, unmaintained equipment; it is a serious finding.
  • Recovering the key to prove the finding. The finding follows from the standard in use; breaking the client's network to demonstrate it is unnecessary and reads their traffic.

Quick revision

  • WEP (Wired Equivalent Privacy): the first Wi-Fi encryption standard, using the RC4 cipher with a per-frame initialisation vector.
  • Fatal mistakes: the IV was too short so it repeats on a busy network (reusing the keystream, a known cryptographic weakness), the IV was sent in the clear, and the key/IV combination was statistically weak, so enough captured frames allow the key itself to be recovered.
  • Consequence: passively capturing enough traffic recovers the key in minutes, giving full access. Treat WEP as no encryption at all; never use or accept it. A WEP network is a serious finding and usually indicates old equipment.
  • The lesson: a standard cipher used wrongly (short reused IV) gave no security, defining what WPA, WPA2 and WPA3 had to fix.

Test yourself

  1. Why is WEP described as comprehensively broken rather than merely weak?

Because a flaw in how it used its cipher allows an attacker who passively captures enough traffic to recover the network's key itself through analysis, not merely to decrypt individual frames, and on a busy network this takes only minutes. Once the key is recovered the attacker can decrypt all traffic and join the network, so WEP provides effectively no protection against anyone who bothers, which is why a WEP network should be treated as having no encryption at all.

  1. What was WEP's fatal mistake, and how does it illustrate a wider lesson?
munotes.in482

WEP and Why It Broke

Its fatal mistake was in how it used the RC4 cipher: the initialisation vector was too short, so it repeated on a busy network, causing keystream reuse, it was sent in the clear, and the key and IV were combined in a statistically weak way, so enough captured frames revealed the key. It illustrates the wider lesson that real cryptographic failures are sound primitives used wrongly, since RC4 was a standard cipher and WEP failed in the details of its use, not in an exotic algorithm.

  1. Why is keystream reuse, caused by repeating initialisation vectors, a serious weakness?

Because a stream cipher produces a keystream from the key and the initialisation vector, and if the same key and IV are used for two frames, the same keystream encrypts both, which leaks information relating the two frames and, combined with WEP's other weaknesses, contributes to recovery of the key. Reusing a keystream is exactly the cryptographic weakness that requires initialisation vectors to be unique, and WEP's short IV made repetition inevitable.

  1. Why is the false sense of security from WEP considered worse than no encryption?

Because WEP's presence suggests the network is protected while it provides effectively none, so users and administrators believe their traffic is confidential when the key can be recovered in minutes and the traffic fully exposed. A network known to be unencrypted at least prompts caution, whereas one wrongly believed secure invites the transmission of sensitive data over what is effectively an open link.

  1. How should a WEP network be handled, and why is breaking it unnecessary to report the finding?

It should be replaced immediately with WPA2 using AES at minimum, or WPA3, and the equipment replaced if it supports only WEP, since a WEP network is effectively unencrypted and usually indicates old, unmaintained equipment. Breaking it to demonstrate the weakness is unnecessary because the finding follows directly from the standard in use, which is established from the network's beacon, so recovering the key would needlessly read the client's traffic without adding to the conclusion.

Contents This chapter on its own page

munotes.in483

Chapter One Hundred Five

WPA and WPA2: AES and the Four-Way Handshake

Syllabus topic Module 2, "Wireless Network Security and Authentication Mechanisms: Compare WEP, WPA, WPA2, WPA3 protocols"

In one line

WPA was a stop-gap that fixed WEP's worst problems on the same hardware but is now superseded. WPA2 replaced the cipher with strong AES and became the long-standing standard; its remaining weakness is that capturing the four-way handshake lets an attacker guess a weak passphrase offline.

In examination wording: Wi-Fi Protected Access was introduced as a transitional replacement for WEP, using TKIP on existing hardware; WPA2 adopted AES in CCMP mode and became the standard for over a decade; both establish per-session keys through a four-way handshake, the capture of which permits offline dictionary attack against the passphrase in the personal mode.

WPA: the stop-gap

When WEP was shown to be broken, a replacement was needed urgently, and it had to run on the existing hardware, which could not be quickly replaced. So WPA was designed as a transitional fix: it addressed WEP's worst weaknesses while working on the same devices.

WPA kept the RC4 cipher (for hardware compatibility) but added TKIP (Temporal Key Integrity Protocol), which changed the key frequently and fixed the initialisation-vector reuse that broke WEP, so the specific attacks on WEP no longer worked. It was a genuine improvement and it bought time.

But WPA was always a stop-gap, not a destination. Keeping RC4 and building on the same foundations, it was later shown to have its own weaknesses, and it is now superseded. A network on WPA (with TKIP) today is a finding: it should be on WPA2 or WPA3. The lesson WPA teaches is that a compatibility-driven transitional fix is not a place to stay; it is a bridge to the real replacement.

WPA2: the long-standing standard

WPA2 was the real replacement, and it made the decisive change: it replaced the stream cipher with AES (the strong block cipher from the encryption chapters) in a mode called CCMP, which provides both confidentiality and integrity. This is genuinely strong encryption, correctly used, and it is why WPA2 was the standard for well over a decade and remains acceptable today when configured well.

With WPA2-AES, the cipher is not the weakness (unlike WEP). The remaining weaknesses are elsewhere: in the handshake (below) and, above all, in the passphrase, because WPA2-Personal is only as strong as the passphrase chosen. So the story changes from WEP: the encryption is sound, and the weak points are the handshake and human passphrase choice.

WPA2 comes in two modes, worth naming because the next chapter and the best-practice chapter use them:

  • WPA2-Personal (pre-shared key): everyone uses the same shared passphrase. Simple, and its security rests on that passphrase.
  • WPA2-Enterprise: each user authenticates individually (with their own credentials, via a central authentication server), so there is no single shared passphrase. Stronger, and used by organisations.
munotes.in484

WPA and WPA2: AES and the Four-Way Handshake

The four-way handshake

When a device joins a WPA2 network, it and the access point perform a four-way handshake to confirm they share the passphrase (or the credentials) and to derive the session keys that will encrypt the traffic. Understanding it is essential, because its weakness is exactly what WPA3 fixes.

At concept level, the four-way handshake:

  • confirms that both sides know the shared secret (the passphrase, in Personal mode), without sending the passphrase itself;
  • derives fresh session keys from the shared secret and some exchanged random values, so each session uses different keys.

The security weakness, and the examinable point: an attacker who captures the four-way handshake (which, as the wireless-basics chapter established, requires only being in range, and can be prompted by forcing a device to reconnect) obtains enough information to test passphrase guesses offline. They cannot read the traffic from the handshake alone, and they do not learn the passphrase directly, but they can take the captured handshake away and, on their own hardware, try passphrases against it at full speed, exactly the offline attack from the password block. If the passphrase is weak, it falls to this offline guessing.

So WPA2-Personal's practical weakness is: capturing the handshake enables offline guessing of the passphrase, so a weak passphrase is the real break. The encryption is strong; the passphrase is the soft point, and this is why the password block's arithmetic (length wins) applies directly to Wi-Fi passphrases, and why a long passphrase matters. WPA2-Enterprise avoids this, because there is no single shared passphrase to guess; each user authenticates individually.

The comparison so far

Placing WEP, WPA and WPA2 side by side, which is what MU asks:

WEPWPAWPA2
CipherRC4, broken useRC4 with TKIP (stop-gap)AES (CCMP)
StatusBroken; never useSupersededThe long-standing standard, still acceptable
Main weaknessKey recoverable from captured trafficTKIP later weakenedThe handshake (offline guessing) and weak passphrases
Key protectionFails (key recovered)ImprovedSound cipher; passphrase is the soft point

The trajectory is the block's story: WEP broken outright, WPA a transitional patch, WPA2 the sound standard whose remaining weakness is the handshake and the passphrase, which sets up WPA3.

A worked example, framed defensively

An assessor surveys a client's wireless standards, from beacons (passive), on the client's own networks with authorisation.

  • One network uses WPA (TKIP). Finding: superseded and weaker than WPA2; move to WPA2-AES or WPA3.
  • The main network uses WPA2 with AES, which is acceptable. The assessor notes that its security now rests on the passphrase, because capturing the four-way handshake would allow offline guessing; if the passphrase is weak, the network is at risk. Recommendation: ensure a long, strong passphrase (the password block's length argument), and consider WPA3 (next chapter) for its handshake improvement.
  • The organisation's staff network uses WPA2-Enterprise, with individual authentication. Recorded as the stronger choice, since there is no shared passphrase to guess offline.
  • The assessor does not capture a handshake and attempt to crack the passphrase, which would be attacking the network; the weakness follows from the standard and mode in use, established from the beacon, and the recommendation is a strong passphrase or Enterprise mode.
munotes.in485

WPA and WPA2: AES and the Four-Way Handshake

The report places the client's networks on the WEP-to-WPA2 trajectory, notes that WPA2-AES is sound but rests on the passphrase because of the four-way handshake's offline-guessing weakness, and recommends strong passphrases, Enterprise mode where possible, and WPA3. The assessor establishes the findings from the advertised standards, not by cracking the client's Wi-Fi.

What beginners get wrong

  • Treating WPA (TKIP) as current. It was a stop-gap for old hardware, is superseded, and is a finding today; use WPA2-AES or WPA3.
  • Thinking WPA2's weakness is the cipher. AES is strong; the weaknesses are the four-way handshake (offline guessing) and weak passphrases, not the cipher.
  • Missing why capturing the handshake matters. It does not reveal the passphrase or the traffic directly, but it lets an attacker test passphrase guesses offline at full speed, so a weak passphrase falls.
  • Underrating the passphrase. On WPA2-Personal the passphrase is the real security, because of the handshake; the length arithmetic from the password block applies directly.
  • Overlooking Enterprise mode. WPA2-Enterprise authenticates each user individually, avoiding a single shared passphrase to guess, and is stronger for organisations.
  • Cracking the passphrase to prove the finding. The offline-guessing weakness follows from the standard and mode in use; capturing and cracking the client's handshake is unnecessary and attacks the network.

Quick revision

  • WPA: a transitional stop-gap for WEP on the same hardware, keeping RC4 but adding TKIP to fix IV reuse; now superseded and a finding today.
  • WPA2: replaced the cipher with AES (CCMP), providing confidentiality and integrity; the long-standing standard, still acceptable well configured. The cipher is not the weakness.
  • Modes: WPA2-Personal (shared passphrase; security rests on it) and WPA2-Enterprise (each user authenticates individually; no shared passphrase).
  • The four-way handshake derives session keys and confirms the shared secret without sending it; capturing it enables offline guessing of the passphrase, so on Personal mode a weak passphrase is the real break (the password block's length argument applies). Enterprise avoids this.

Test yourself

  1. Why was WPA introduced, and why is it now considered a stop-gap?

WPA was introduced as an urgent transitional replacement for the broken WEP that could run on existing hardware which could not be quickly replaced, keeping the RC4 cipher but adding TKIP to fix WEP's initialisation-vector reuse, so the specific WEP attacks no longer worked. It is a stop-gap because, built for compatibility on the same foundations, it was later shown to have its own weaknesses and is now superseded, so it is a bridge to WPA2 rather than a destination.

munotes.in486

WPA and WPA2: AES and the Four-Way Handshake

  1. What decisive change did WPA2 make, and where does its remaining weakness lie?

WPA2 replaced the stream cipher with AES in CCMP mode, providing strong confidentiality and integrity, so the cipher is genuinely sound and became the standard for over a decade. Its remaining weakness lies not in the cipher but in the four-way handshake, whose capture permits offline passphrase guessing, and above all in the passphrase itself in Personal mode, since WPA2-Personal is only as strong as the passphrase chosen.

  1. What does the four-way handshake do, and why is its capture a weakness?

It confirms that a joining device and the access point share the secret, without sending the passphrase itself, and derives fresh session keys from that secret and exchanged random values so each session uses different keys. Its capture is a weakness because an attacker who records it obtains enough information to test passphrase guesses offline on their own hardware at full speed, so although the handshake reveals neither the passphrase nor the traffic directly, a weak passphrase will fall to offline guessing.

  1. Why does the password block's argument that length beats complexity apply directly to WPA2?

Because on WPA2-Personal the practical break is offline guessing of the passphrase after capturing the four-way handshake, which is exactly the offline password attack from the password block, limited only by the attacker's hardware and the passphrase's strength. Since the keyspace grows exponentially with length, a long passphrase makes offline guessing infeasible, so the same reasoning that favours length over mandated complexity for passwords applies to Wi-Fi passphrases.

  1. How does WPA2-Enterprise avoid the passphrase weakness of WPA2-Personal?

By having each user authenticate individually with their own credentials through a central authentication server, so there is no single shared passphrase used by everyone. Because there is no shared passphrase to capture and guess offline, the offline-guessing weakness of the Personal mode's four-way handshake does not apply in the same way, which makes Enterprise mode the stronger choice for organisations.

Contents This chapter on its own page

munotes.in487

Chapter One Hundred Six

WPA3 and the SAE Handshake

Syllabus topic Module 2, "Wireless Network Security and Authentication Mechanisms: Compare WEP, WPA, WPA2, WPA3 protocols"

In one line

WPA3 is the current standard, and its central improvement is a new handshake, SAE, designed so that capturing it does not enable offline guessing of the passphrase, fixing exactly WPA2's main weakness. It keeps AES, and adds forward secrecy and protected management frames.

In examination wording: WPA3 is the current wireless security standard, retaining AES encryption but replacing the four-way handshake's key establishment with Simultaneous Authentication of Equals, which resists offline dictionary attack because each guess requires a fresh interaction with the network; it also provides forward secrecy and mandatory protection of management frames.

WPA3 as the answer to a specific weakness

The previous chapter left WPA2 with one main practical weakness: capturing the four-way handshake lets an attacker guess the passphrase offline, at full speed on their own hardware, so a weak passphrase falls. WPA3's central purpose is to fix exactly that weakness, and teaching it as the targeted answer is the cleanest way to understand it.

WPA3 keeps what WPA2 got right, the strong AES cipher, and changes what WPA2 got wrong, the handshake. So the comparison the block builds resolves neatly: WEP broken, WPA a stop-gap, WPA2 sound but for its handshake and passphrase, WPA3 the same soundness with the handshake weakness removed.

The SAE handshake

WPA3-Personal replaces the key-establishment step with a handshake called SAE (Simultaneous Authentication of Equals, sometimes called the Dragonfly handshake). The concept-level point is not the cryptographic detail but what it achieves:

Under WPA2, capturing the handshake gave the attacker something they could take away and test guesses against offline, so the attacker could try millions of passphrases per second without further contact with the network. Under SAE, capturing the handshake does not give the attacker that: the design requires that each passphrase guess involve a fresh interaction with the network, so an attacker cannot grind millions of guesses against a captured file offline. They would have to make each guess by actually interacting with the access point, which is slow, detectable, and rate-limitable.

So SAE removes the offline-guessing attack. The consequence is that a captured WPA3 handshake is not the springboard for offline passphrase cracking that a WPA2 handshake is, which is the central security improvement and the reason WPA3 exists. It also means that even a somewhat weaker passphrase is far more resistant under WPA3 than under WPA2, because the attacker cannot use offline speed against it, though a strong passphrase is still recommended.

The other improvements

WPA3 adds two more protections a student should know:

Forward secrecy. WPA3 provides forward secrecy, the property from the encryption chapters: each session's keys are derived so that compromising the passphrase later does not decrypt previously captured traffic. Under this, an attacker who records encrypted traffic and only later obtains the passphrase cannot go back and decrypt the recorded traffic, because the session keys were not simply derivable from the passphrase. This limits the damage of a passphrase compromise, exactly as forward secrecy limited the damage of the Heartbleed key exposure.

munotes.in488

WPA3 and the SAE Handshake

Protected management frames. WPA3 makes protection of management frames mandatory. The wireless-basics chapter noted that some management frames are, in older standards, unauthenticated, which enables attacks like deauthentication (the next chapter). Protecting management frames defends against a class of those attacks, hardening the network against forced disconnection and certain spoofing.

WPA3 also improves the experience of open networks (with opportunistic encryption for networks that have no passphrase) and strengthens the Enterprise mode, but the examinable core is the SAE handshake, forward secrecy, and protected management frames.

The completed comparison

The four standards, side by side, which is MU's explicit request:

WEPWPAWPA2WPA3
CipherRC4 (broken use)RC4 + TKIPAES (CCMP)AES
Key establishment(weak)(improved)Four-way handshakeSAE
Offline passphrase guessing from a capturen/a (key recovered)possiblepossible (the weakness)prevented
Forward secrecyNoNoNoYes
Management-frame protectionNoNoOptionalMandatory
StatusBroken; never useSupersededLong standard; acceptableCurrent; preferred

Read across the "offline passphrase guessing" row and the story of the block is visible: WEP surrenders the key, WPA2 leaves the passphrase guessable offline, and WPA3 closes that. WPA3 is the current standard and the preferred choice where the hardware supports it.

A worked example, framed defensively

An assessor reviews a client's wireless standards and recommends the target state, from beacons (passive), on the client's own networks with authorisation.

  • The main network is WPA2-AES. Acceptable, but its security rests on the passphrase because of the four-way handshake's offline-guessing weakness. Recommendation: move to WPA3 where the access points and devices support it, because SAE removes the offline-guessing weakness, and WPA3 adds forward secrecy and protected management frames.
  • Some older devices support only WPA2. The assessor notes the practical reality: a transition period may run WPA2/WPA3 mixed mode, and until all devices support WPA3, a strong passphrase remains essential because WPA2's weakness still applies to the WPA2 clients.
  • The assessor recommends management-frame protection (mandatory in WPA3, available as an option on WPA2) to defend against the deauthentication attacks of the next chapter.
  • The assessor does not capture handshakes or attempt cracking; the recommendation follows from the standards in use and their known properties.

The report resolves the block's comparison for the client: WPA3 is the target because it fixes WPA2's offline-guessing weakness and adds forward secrecy and management-frame protection, with a strong passphrase essential during any WPA2 transition. The assessor establishes everything from the advertised standards, not by attacking the network.

munotes.in489

WPA3 and the SAE Handshake

What beginners get wrong

  • Not knowing what WPA3 specifically fixes. Its central improvement is the SAE handshake, which prevents the offline passphrase guessing that capturing a WPA2 handshake enables; that is the point of WPA3.
  • Thinking WPA3 changed the cipher. It keeps AES; it changed the key establishment (SAE) and added forward secrecy and management-frame protection.
  • Believing SAE lets an attacker read traffic from a captured handshake. It prevents offline guessing by requiring each guess to involve a fresh interaction with the network, so a captured handshake is not a springboard for offline cracking.
  • Overlooking forward secrecy. WPA3 ensures that obtaining the passphrase later does not decrypt previously captured traffic, limiting the damage of a passphrase compromise.
  • Ignoring management-frame protection. WPA3 makes it mandatory, defending against deauthentication and certain spoofing attacks that exploit unauthenticated management frames.
  • Assuming a strong passphrase no longer matters on WPA3. SAE makes even a weaker passphrase far more resistant, but a strong passphrase is still recommended, and it remains essential wherever WPA2 clients are present.

Quick revision

  • WPA3 is the current standard; it keeps AES and replaces the key establishment with the SAE handshake.
  • SAE's central improvement: capturing the handshake does not enable offline passphrase guessing, because each guess requires a fresh interaction with the network, so the attacker cannot grind millions of guesses against a captured file. This fixes exactly WPA2's main weakness.
  • Also: forward secrecy (obtaining the passphrase later does not decrypt previously captured traffic) and mandatory protected management frames (defends against deauthentication and spoofing).
  • Comparison resolved: WEP broken, WPA superseded, WPA2 sound but offline-guessable via the handshake, WPA3 closes the offline-guessing weakness and is preferred. During a WPA2 transition, a strong passphrase remains essential.

Test yourself

  1. What weakness of WPA2 does WPA3 specifically fix, and how?

WPA3 fixes WPA2's weakness that capturing the four-way handshake lets an attacker guess the passphrase offline at full speed. It does so by replacing the key establishment with the SAE handshake, which is designed so that each passphrase guess requires a fresh interaction with the network, so an attacker cannot take a captured handshake away and grind millions of guesses against it offline, removing the offline-guessing attack.

  1. Does WPA3 change the encryption cipher, and what does it change?

No; WPA3 retains AES, the strong cipher that WPA2 already used correctly. What it changes is the key establishment, replacing the four-way handshake with the SAE handshake to prevent offline passphrase guessing, and it adds forward secrecy and makes protection of management frames mandatory. The soundness of WPA2's cipher was not the problem, so it was kept.

  1. What does forward secrecy provide in WPA3, and why does it matter?
munotes.in490

WPA3 and the SAE Handshake

Forward secrecy ensures that each session's keys are derived so that compromising the passphrase at a later time does not allow decryption of traffic captured earlier. It matters because an attacker who records encrypted traffic and only afterwards obtains the passphrase cannot go back and decrypt the recorded traffic, so a passphrase compromise does not retrospectively expose past sessions, limiting its damage in the same way forward secrecy limited the impact of the Heartbleed key exposure.

  1. What is the security value of mandatory protected management frames in WPA3?

Because some management frames were unauthenticated in older standards, they could be forged, enabling attacks such as deauthentication that force a device to disconnect, and certain spoofing. WPA3 makes protection of management frames mandatory, which authenticates them and defends against that class of attacks, hardening the network against forced disconnection and related manipulation.

  1. Why does a strong passphrase remain essential during a transition to WPA3?

Because until all devices support WPA3 a network may run in a mixed mode that still serves WPA2 clients, and for those clients the WPA2 weakness applies: capturing their four-way handshake enables offline passphrase guessing. So while SAE protects WPA3 clients, a weak passphrase would still be crackable through the WPA2 clients, making a strong passphrase essential until the network is fully WPA3.

Contents This chapter on its own page

munotes.in491

Chapter One Hundred Seven

Wireless Attacks: Deauthentication, Evil Twins and Rogue Access Points

Syllabus topic Module 2, "Wireless Network Security and Authentication Mechanisms: ... wireless sniffing risks, rogue access points"

In one line

Three wireless attacks a defender must recognise: deauthentication (forcing a device off the network by forging an unauthenticated management frame), the evil twin (a fake access point imitating a real network's name to lure devices), and the rogue access point (an unauthorised access point plugged into a network, opening a back door). Each has a clear defence.

In examination wording: wireless networks are subject to attacks exploiting the broadcast medium and unauthenticated management frames; a deauthentication attack forcibly disconnects a client by forging deauthentication frames; an evil twin is a rogue access point impersonating a legitimate network's SSID to intercept connections; a rogue access point is an unauthorised access point attached to an organisation's network, and each is countered by protected management frames, mutual authentication, and network monitoring respectively.

Deauthentication: forcing a device off

The wireless-basics chapter noted that some management frames are, in older standards, unauthenticated, meaning a device accepts them without checking who sent them. The deauthentication frame, which legitimately tells a device to disconnect, is one of these. Because it is unauthenticated in older standards, an attacker in range can forge one, sending a device a deauthentication frame that appears to come from the access point, and the device, unable to tell it is forged, disconnects.

What this achieves for an attacker, and why a defender must know it:

  • Denial of service: repeatedly deauthenticating devices keeps them off the network, a wireless denial of service (the denial-of-service block's theme, in wireless form).
  • Enabling other attacks: forcing a device to disconnect makes it reconnect, and reconnection produces a fresh four-way handshake for the attacker to capture (the WPA2 chapter's offline-guessing setup), or an opportunity to lure the device to an evil twin (below). So deauthentication is often a step, not an end.

Detection and defence. From the defender's side, a burst of deauthentication frames, or devices repeatedly and unexpectedly disconnecting, is the sign. The defence is the WPA3 chapter's protected management frames (mandatory in WPA3, optional in WPA2), which authenticate management frames so a forged deauthentication is rejected. This is a concrete reason to prefer WPA3, and it is the examinable countermeasure.

The evil twin: a fake network with a real name

An evil twin is a fake access point that advertises the same SSID (network name) as a legitimate network, so that devices and users, seeing the familiar name, connect to the attacker's access point instead of the real one. Because, as the wireless-basics chapter established, the SSID is just a name that anyone can broadcast, nothing stops an attacker naming their access point after a real network.

Why it is dangerous:

  • Once a device connects to the evil twin, the attacker is the network the device talks through, so they are positioned to intercept the device's traffic, the man-in-the-middle position from the interception block, achieved by impersonating the network.
  • It is often combined with deauthentication: the attacker deauthenticates the device from the real network, and the device, reconnecting, may associate with the stronger-signal evil twin.
  • Public places, where users expect open networks with familiar names, are the classic setting, which is why the browsing-safety advice is to treat open networks as hostile.
munotes.in492

Wireless Attacks: Deauthentication, Evil Twins and Rogue Access Points

Detection and defence. The defences are the ones the encryption block already built:

  • Mutual authentication. On WPA2/WPA3-Enterprise, the device can verify the network's certificate, so an evil twin that cannot present the real certificate is detected and rejected. This is the strongest defence and a reason organisations use Enterprise mode.
  • Do not auto-connect to open networks by name, and treat any open network as untrusted; use a VPN or ensure end-to-end encryption (the transport-security chapters) so that even an evil twin sees only encrypted traffic.
  • Monitoring for unexpected access points advertising the organisation's SSID.

The examinable point: the evil twin exploits that an SSID is only a name; the defence is authenticating the network (Enterprise certificates) and protecting the traffic end to end so impersonation gains nothing.

The rogue access point: an unauthorised door

A rogue access point is an unauthorised access point connected to the organisation's network, whether plugged in by a well-meaning employee wanting better Wi-Fi coverage or by an attacker who gained physical access. Either way, it creates a wireless entry point into the network that is not under the organisation's security control.

Why it is a serious finding:

  • It bypasses the perimeter. The organisation may have a carefully secured official Wi-Fi, but a rogue access point plugged into an internal network port opens a parallel, unsecured way in, often with weak or no encryption, undoing the perimeter (the network-architecture chapters).
  • The well-meaning employee's rogue access point is as dangerous as the attacker's, because it is equally outside the security controls; intent does not change the exposure.

Detection and defence. This is a monitoring and control problem:

  • Wireless monitoring / scanning to detect access points broadcasting on the organisation's premises that are not on the authorised list. Regular wireless surveys find rogue access points.
  • Network access control on the wired network, so that an unauthorised device plugged into a port is not simply granted access (the authentication and segmentation chapters).
  • Policy: a clear rule that only IT may attach access points, so the well-meaning employee knows not to, with sanctioned coverage solutions provided so the need does not arise.

The examinable point: a rogue access point is an unauthorised access point on the network that bypasses the perimeter, detected by wireless monitoring and controlled by network access control and policy.

munotes.in493

Wireless Attacks: Deauthentication, Evil Twins and Rogue Access Points

Why these three belong together

The three attacks are the wireless-specific risks MU names, and they share the block's governing fact: because Wi-Fi is broadcast and older management frames are unauthenticated, an attacker in range can forge frames (deauthentication), impersonate a network (evil twin), or attach an unauthorised one (rogue access point). And their defences draw the block together: protected management frames (WPA3), network authentication (Enterprise mode), and monitoring. So the wireless block resolves into a short defensive checklist, which the next chapter states in full.

A worked example, framed defensively

A wireless security assessment of an organisation, conducted with authorisation on the organisation's own environment, reports at concept level.

  • Staff report intermittent disconnections. The assessor notes this is consistent with a deauthentication condition (whether an attack or interference) and recommends enabling protected management frames by moving to WPA3, which authenticates management frames and rejects forged deauthentications.
  • A wireless scan finds an access point advertising the organisation's SSID from an unexpected location, a possible evil twin. Recommendation: use Enterprise authentication so devices verify the network's certificate and reject impersonators, and ensure traffic is encrypted end to end so interception gains nothing. The assessor does not set up an evil twin or capture anyone's traffic; the finding is the observed unexpected access point.
  • The scan finds an unauthorised access point plugged into an internal port, a rogue access point installed by an employee for convenience. A serious finding: it bypasses the perimeter. Recommendation: remove it, implement network access control and a policy that only IT may attach access points, and provide sanctioned coverage.
  • Throughout, the assessor detects and reports; the recommendations are protected management frames, Enterprise authentication, and monitoring with access control.

The report covers the three wireless attacks MU names, each as a detection-and-defence finding, and resolves them into the block's countermeasures. The assessor recognises the attacks from their signs on the organisation's own network, and does not mount them.

What beginners get wrong

  • Thinking a deauthentication attack breaks the encryption. It does not; it forces a disconnection by forging an unauthenticated management frame, causing denial of service or prompting a reconnection the attacker can exploit. The defence is protected management frames.
  • Believing an evil twin is sophisticated. Its power is simply that an SSID is only a name anyone can broadcast; the defence is authenticating the network (Enterprise certificates) and protecting traffic end to end.
  • Treating a rogue access point as only an attacker's tool. A well-meaning employee's unauthorised access point is equally dangerous, because it is equally outside the security controls; intent does not change the exposure.
  • Missing that these combine. Deauthentication forces a reconnection that can capture a handshake or drive a device to an evil twin; they are often steps in a chain.
  • Overlooking monitoring. Rogue access points and evil twins are found by wireless scanning for unexpected access points; without monitoring they go unnoticed.
  • Forgetting the WPA3 connection. Protected management frames, mandatory in WPA3, are the defence against deauthentication, a concrete reason to prefer WPA3.
munotes.in494

Wireless Attacks: Deauthentication, Evil Twins and Rogue Access Points

Quick revision

  • Deauthentication: forging an unauthenticated management frame to force a device to disconnect; causes denial of service, or prompts a reconnection the attacker exploits (capture a handshake, drive to an evil twin). Defence: protected management frames (WPA3).
  • Evil twin: a fake access point advertising a legitimate network's SSID to lure devices, giving the attacker a man-in-the-middle position. Works because an SSID is only a name. Defence: Enterprise authentication (verify the network's certificate) and end-to-end encryption; treat open networks as hostile.
  • Rogue access point: an unauthorised access point on the organisation's network, bypassing the perimeter, dangerous whether malicious or well-meaning. Defence: wireless monitoring, network access control, and policy.
  • All three follow from the broadcast medium and unauthenticated frames; the defences (protected management frames, Enterprise authentication, monitoring) resolve the block.

Test yourself

  1. How does a deauthentication attack work, and what is its defence?

It exploits that deauthentication frames are unauthenticated in older wireless standards, so an attacker in range forges a deauthentication frame that appears to come from the access point, and the target device, unable to tell it is forged, disconnects. This causes a denial of service if repeated, or prompts a reconnection the attacker can exploit to capture a fresh four-way handshake or drive the device to an evil twin. Its defence is protected management frames, mandatory in WPA3, which authenticate management frames so a forged deauthentication is rejected.

  1. What is an evil twin, why is it effective, and how is it countered?

An evil twin is a fake access point that advertises the same SSID as a legitimate network, so devices and users connect to it instead of the real network, giving the attacker a man-in-the-middle position to intercept traffic. It is effective because an SSID is merely a name that anyone can broadcast, so nothing inherently stops impersonation, and it is often paired with deauthentication to drive devices across. It is countered by mutual authentication in Enterprise mode, where the device verifies the network's certificate and rejects an impersonator, and by end-to-end encryption so that interception yields only encrypted traffic.

  1. What is a rogue access point, and why is a well-meaning employee's one still dangerous?

A rogue access point is an unauthorised access point connected to the organisation's network, creating a wireless entry point outside the organisation's security control. A well-meaning employee's rogue access point, installed for better coverage, is still dangerous because it is equally outside the security controls and often has weak or no encryption, so it bypasses the carefully secured perimeter exactly as an attacker's would; the intent does not change the exposure it creates.

munotes.in495

Wireless Attacks: Deauthentication, Evil Twins and Rogue Access Points

  1. How are evil twins and rogue access points detected?

By wireless monitoring and scanning: regularly surveying the wireless environment for access points that are not on the authorised list, which reveals both a rogue access point broadcasting from inside the premises and an evil twin advertising the organisation's SSID from an unexpected location. Without such monitoring these access points go unnoticed, so detection depends on knowing the authorised set and watching for departures from it, complemented by network access control on the wired side.

  1. Why do the three wireless attacks belong together, and how do their defences resolve the block?

They belong together because all three follow from the block's governing facts, that Wi-Fi is broadcast so anyone in range participates, and that older management frames are unauthenticated, which lets an attacker forge frames, impersonate a network, or attach an unauthorised one. Their defences resolve the block into a checklist: protected management frames from WPA3 defeat deauthentication, Enterprise authentication defeats the evil twin by letting devices verify the network, and monitoring with access control defeats the rogue access point, tying the encryption comparison and the best-practice chapter together.

Contents This chapter on its own page

munotes.in496

Chapter One Hundred Eight

Wireless Best Practice and Enterprise Authentication

Syllabus topic Module 2, "Wireless Network Security and Authentication Mechanisms: ... wireless security best practices"

In one line

Wireless best practice is the short checklist that follows from the block: use WPA3 (or WPA2-AES at least), a long passphrase, Enterprise authentication where possible, protected management frames, and monitoring for rogue and evil-twin access points; do not rely on hiding the SSID. Enterprise authentication, the recurring stronger choice, means each user authenticates individually rather than sharing one passphrase.

In examination wording: wireless security best practice comprises using the strongest available protocol (WPA3, or WPA2 with AES), a long passphrase resistant to offline guessing, WPA2/WPA3-Enterprise authentication with individual credentials and a central authentication server where feasible, mandatory protected management frames, network monitoring for rogue access points, and not relying on SSID concealment as a security control.

The checklist the block earned

Every item on the best-practice checklist is a conclusion the block already reached, so the chapter is a synthesis, not new material. Stated as the checklist a defender applies:

  1. Use the strongest protocol available: WPA3, falling back to WPA2 with AES where WPA3 is not yet supported. Never WEP (broken) or WPA/TKIP (superseded). This is the encryption-comparison chapters' conclusion.
  2. Use a long passphrase. On Personal mode, the passphrase is the real security, because capturing the four-way handshake enables offline guessing; the password block's length argument applies directly, so a long passphrase is essential.
  3. Prefer Enterprise authentication where the organisation can run it (below), because it removes the shared passphrase entirely and enables the device to verify the network, defeating evil twins.
  4. Enable protected management frames (mandatory in WPA3, optional in WPA2), which defeat the deauthentication attack.
  5. Monitor for rogue and evil-twin access points, with wireless scanning and network access control, since these are found only by looking.
  6. Do not rely on hiding the SSID, which is obscurity, not security; it may be a minor measure but never a control.

That is the whole of wireless best practice at this level, and each item carries its reason from an earlier chapter, which is how a student should be able to present it: not as a list to memorise but as conclusions with reasons.

Enterprise authentication, settled

Enterprise authentication has been the recurring "stronger choice" through the block; this chapter settles what it is, because the student should be able to explain it.

WPA2/WPA3-Personal uses a single pre-shared key, one passphrase everyone shares. Its weaknesses followed: the passphrase can be guessed offline after capturing the handshake, everyone knowing it means it is widely exposed, and changing it means telling everyone.

WPA2/WPA3-Enterprise replaces the shared passphrase with individual authentication: each user authenticates with their own credentials (typically their organisational username and password, or a certificate), verified by a central authentication server (using a framework the student can name at concept level as 802.1X with a RADIUS server, but the point is individual credentials against a central server). The consequences are all improvements:

munotes.in497

Wireless Best Practice and Enterprise Authentication

  • No shared passphrase to guess. Since there is no single pre-shared key, the offline-guessing attack on a shared passphrase does not apply in the same way, removing the Personal mode's central weakness.
  • Individual accountability and control. Each user's access can be granted or revoked individually, without changing anything for anyone else, and access is tied to identity.
  • The device can verify the network. Enterprise authentication uses certificates that let the device confirm it is talking to the real network, which is the defence against the evil twin from the previous chapter.

So Enterprise authentication is stronger because it removes the shared passphrase, gives individual control, and lets the device authenticate the network. Its cost is the infrastructure: a central authentication server to run, which is why small networks use Personal mode with a long passphrase and organisations use Enterprise. The examinable contrast is Personal (one shared passphrase, simple, its security resting on that passphrase) versus Enterprise (individual credentials against a central server, stronger, requiring infrastructure).

The block, resolved

The wireless block began with one fact, that Wi-Fi is broadcast so anyone in range receives it, and everything followed from it: encryption is not optional; WEP got it wrong and is broken; WPA was a stop-gap; WPA2 got the cipher right but left the handshake and passphrase as the soft points; WPA3 fixed the handshake and added protected management frames; the wireless attacks exploit the broadcast medium and unauthenticated frames; and best practice is the checklist that answers all of it. A student who can tell that story, from the governing fact to the checklist, understands the block as MU intends.

A worked example, framed defensively

An assessor delivers wireless best-practice recommendations to an organisation, on its own environment with authorisation, at concept level.

  • The organisation runs WPA2-Personal with a shared passphrase across the staff network. Recommendations: move to WPA3 for the SAE handshake and mandatory protected management frames; more importantly for a staff network, move to Enterprise authentication so each employee uses individual credentials against the central authentication server, removing the shared passphrase, enabling individual revocation (important when staff leave), and letting devices verify the network against evil twins.
  • The guest network, where Enterprise is impractical, should stay on WPA3 (or WPA2-AES) with a long passphrase, rotated periodically, and isolated from the internal network (segmentation).
  • Protected management frames enabled (via WPA3) to defeat deauthentication; wireless monitoring established to detect rogue and evil-twin access points; network access control on wired ports.
  • The organisation had hidden the SSID believing it secured the network. Corrected: obscurity, not security; keep it if desired but never rely on it.
munotes.in498

Wireless Best Practice and Enterprise Authentication

The report is the block's checklist applied: strongest protocol, Enterprise for staff and a long passphrase for guests, protected management frames, monitoring, and the SSID correction, each with its reason. The assessor recommends from the standards and configuration, demonstrating nothing by attack.

What beginners get wrong

  • Presenting best practice as a list to memorise. Each item is a conclusion with a reason from the block (WPA3 because WEP and the handshake, long passphrase because offline guessing, and so on); understanding the reasons is the point.
  • Not knowing what Enterprise authentication is. It replaces the shared passphrase with individual credentials verified by a central authentication server, which removes the shared-passphrase weakness, gives individual control, and lets the device verify the network.
  • Thinking Enterprise is always the answer. It requires infrastructure (a central authentication server), so small networks correctly use Personal mode with a long passphrase; Enterprise is for organisations.
  • Forgetting the guest network. Where Enterprise is impractical, a long passphrase on WPA3/WPA2-AES, rotated and network-isolated, is the practice.
  • Relying on SSID hiding. It is obscurity; it may be a minor measure but is never a control, a point the block established at the start.
  • Omitting monitoring. Rogue and evil-twin access points are found only by looking; best practice includes wireless monitoring and network access control.

Quick revision

  • Wireless best practice (each item a block conclusion): WPA3 (or WPA2-AES), never WEP/TKIP; long passphrase (offline-guessing defence); Enterprise authentication where feasible; protected management frames (deauthentication defence); monitoring for rogue/evil-twin access points; do not rely on hiding the SSID.
  • Personal mode: one shared pre-shared key (passphrase); simple; security rests on the passphrase, guessable offline after a handshake capture.
  • Enterprise mode: individual credentials against a central authentication server (802.1X/RADIUS at concept level); no shared passphrase, individual grant/revoke, and the device can verify the network (evil-twin defence). Cost: infrastructure.
  • The block resolved: from Wi-Fi is broadcast to the best-practice checklist, every standard and attack a step in between.

Test yourself

  1. What is wireless security best practice, and why is each item more than a rule to memorise?

It is the checklist of using the strongest protocol (WPA3, or WPA2 with AES, never WEP or TKIP), a long passphrase, Enterprise authentication where feasible, protected management frames, monitoring for rogue and evil-twin access points, and not relying on SSID concealment. Each item is more than a rule because it is a conclusion the block reached with a reason: WPA3 because WEP is broken and WPA2's handshake is the weak point, the long passphrase because capturing the handshake enables offline guessing, protected management frames because deauthentication forges unauthenticated frames, and so on, so best practice is a set of reasoned conclusions rather than an arbitrary list.

munotes.in499

Wireless Best Practice and Enterprise Authentication

  1. What is Enterprise authentication, and how does it differ from Personal mode?

Enterprise authentication replaces the single shared passphrase of Personal mode with individual authentication, where each user presents their own credentials, verified by a central authentication server, described at concept level as 802.1X with a RADIUS server. It differs from Personal mode, which uses one pre-shared key that everyone shares, by tying access to individual identity against a central server rather than to a common secret, which changes the security properties substantially.

  1. Why is Enterprise authentication stronger than a shared passphrase?

Because it removes the shared passphrase that is Personal mode's central weakness, so the offline-guessing attack on a captured handshake against a shared passphrase does not apply in the same way; it provides individual accountability and control, so a single user's access can be granted or revoked without affecting others, which matters when staff leave; and it lets the device verify the network through certificates, which is the defence against an evil twin impersonating the network. These three improvements, no shared secret, individual control, and network verification, make it stronger.

  1. When is Personal mode with a long passphrase the correct choice, and how should a guest network be secured?

Personal mode with a long passphrase is correct where the infrastructure for Enterprise authentication, principally a central authentication server, is impractical, such as a home network or a small organisation, and it is also appropriate for a guest network. A guest network should use WPA3, or WPA2 with AES, with a long passphrase rotated periodically, and should be isolated from the internal network by segmentation so that a guest, or an attacker who obtains the guest passphrase, cannot reach internal systems.

  1. How does the wireless block resolve from its governing fact to its best practice?

It begins with the fact that Wi-Fi is broadcast so anyone in range receives every frame, from which encryption is essential; WEP got the encryption wrong and is broken, WPA was a stop-gap, WPA2 got the cipher right but left the four-way handshake and passphrase as the weak points, and WPA3 fixed the handshake and mandated protected management frames; the wireless attacks, deauthentication, evil twin and rogue access point, exploit the broadcast medium and unauthenticated frames; and best practice is the checklist that answers all of it, so the whole block is a single argument from the broadcast medium to the defensive checklist.

Contents This chapter on its own page

munotes.in500

Chapter One Hundred Nine

The Malware Families

Syllabus topic Module 2, "Malware Analysis and Threat Detection: types of malware (viruses, worms, trojans, ransomware, spyware), malware behaviour"

In one line

Malware is software written to do harm, and its families are told apart by two independent questions: how it spreads (needing a host and a user, like a virus; spreading itself, like a worm; or tricking the user, like a trojan) and what it does (encrypt for ransom, spy, steal, give remote control). The block is defensive throughout: recognising and stopping each family.

In examination wording: malware is any software designed to cause harm or gain unauthorised access; its types are classified by propagation mechanism and by payload, where viruses attach to host files and require user action, worms self-propagate across networks, trojans masquerade as legitimate software, and ransomware, spyware and related payloads describe the malicious action performed; effective defence combines the detection methods and endpoint protections examined in this block.

The two questions that classify malware

A student faced with the list of malware types (virus, worm, trojan, ransomware, spyware, and more) should not memorise them as a flat list, because they are not parallel. They answer two different questions, and holding the two questions apart is the organising idea of the whole block:

  1. How does it spread? This is about propagation, the mechanism by which the malware gets onto systems and moves between them. The classic answers are the virus (attaches to a host file, spreads when the user runs the host, needs the user), the worm (spreads itself across networks without needing a user), and the trojan (does not spread on its own but tricks the user into installing it by pretending to be something desirable).
  2. What does it do? This is about the payload, the harmful action once it is running. The answers are ransomware (encrypts files and demands payment), spyware (secretly gathers information), a keylogger (records keystrokes), a remote access tool used maliciously (gives an attacker remote control), and so on.

The two questions are independent, which is the key insight: a piece of malware has both a propagation mechanism and a payload, so real malware is a combination. A trojan (propagation) might carry ransomware (payload); a worm (propagation) might carry spyware (payload). So "is it a worm or is it ransomware?" is a confused question, like asking whether a vehicle is a "diesel" or a "truck": the first names how it is powered, the second what it is for, and a given vehicle is both.

Why this map matters for defence

The map is not academic; it shapes the defence, which is the block's point:

  • Defending against propagation is about stopping malware getting in and spreading: patching (so worms cannot exploit known flaws), user awareness (so trojans do not trick users), network segmentation (so a worm cannot spread freely), and controlling what can run.
  • Defending against the payload is about limiting and detecting the harm: backups (so ransomware's encryption is survivable), least privilege (so a payload can do less), monitoring (so spyware's exfiltration is noticed), and the detection methods of the next chapters.
munotes.in501

The Malware Families

So the two questions map onto two lines of defence, and a complete defence addresses both, stopping malware getting in and spreading, and limiting and detecting what it does if it does. This is why the block covers detection, sandboxing and endpoint protection after the families: those are the defences the map calls for.

The families in this block

MU names the families the block will cover, each placed on the map:

  • Virus (propagation): attaches to a host, needs the user to run it. Next chapter.
  • Worm (propagation): self-propagating across networks. Next chapter.
  • Trojan (propagation by deception): masquerades as legitimate software. Chapter after.
  • Ransomware (payload): encrypts for extortion. Chapter after.
  • Remote access tool used maliciously (payload): remote control. Chapter after.
  • Spyware and keyloggers (payload): covert information gathering. Following chapter.

And then the defences: detection (signature, heuristic, behavioural), safe analysis (the sandbox), and endpoint protection. So the block runs: the map, the families by propagation, the families by payload, and the defences, which is the structure a student should carry.

A note on why the block is defensive

Everything in this block is taught from the defender's side: what each family is, how it behaves (MU's word), how it is detected, and how it is stopped. The block does not teach writing malware, which is both a serious offence under the IT Act (the legal chapters: unauthorised access, damage, and the deployment of malicious code) and outside the purpose of the course, which is defensive understanding. Understanding how malware behaves is exactly what lets a defender recognise and counter it, and that is the block's aim, consistent with the whole book's register.

A worked example, framed defensively

An analyst triages a suspected malware incident, classifying the threat on the two-question map to guide the response, at concept level.

  • The malware arrived as an email attachment the user opened, believing it a document. Propagation: trojan (deception). Defence line: user awareness and controlling what can run.
  • Once running, it encrypted the user's files and displayed a demand. Payload: ransomware. Defence line: backups to recover, and isolation to stop spread.
  • The analyst checks whether it spread to other machines by itself. If it did, it also has a worm propagation aspect, changing the response to include patching and segmentation. If it did not, containment is simpler.
  • The classification drives the response: because it is a trojan-delivered ransomware, recovery is from backups, the entry was user deception (so awareness and execution control are the preventive lessons), and the analyst confirms whether self-propagation (worm behaviour) is present to scope containment.
munotes.in502

The Malware Families

The analyst uses the two-question map to classify propagation and payload, which directly shapes containment and recovery. The work is triage and defence, not creating or operating the malware.

What beginners get wrong

  • Treating the malware types as a flat, parallel list. They answer two independent questions, propagation and payload; a virus or worm is a how-it-spreads, ransomware or spyware is a what-it-does, and real malware combines both.
  • Asking "is it a worm or ransomware?" That confuses the two questions; a worm can carry a ransomware payload, so it is both.
  • Thinking the classification is academic. It maps onto two lines of defence, stopping propagation and limiting the payload, so classifying the threat guides the response.
  • Believing defence is only anti-virus. Anti-virus is part of it, but the map calls for patching, awareness, segmentation, least privilege, backups and monitoring too.
  • Assuming understanding malware means writing it. The block is defensive: how families behave, are detected and are stopped; writing malware is an offence and outside the course.
  • Overlooking that a single sample has both aspects. Every real sample has a propagation mechanism and a payload; naming only one leaves the picture incomplete.

Quick revision

  • Malware: software written to do harm. Classified by two independent questions:
  • How it spreads (propagation): virus (attaches to a host, needs the user), worm (self-propagates across networks), trojan (tricks the user into installing it).
  • What it does (payload): ransomware (encrypts for extortion), spyware/keylogger (covert information gathering), remote access tool used maliciously (remote control).
  • The questions are independent: real malware combines a propagation mechanism and a payload (a trojan carrying ransomware, a worm carrying spyware).
  • The map shapes defence: stop propagation (patching, awareness, segmentation, execution control) and limit the payload (backups, least privilege, monitoring, detection).
  • Block structure: the map, families by propagation (virus, worm), families by payload (trojan-delivered ransomware and remote access, spyware and keyloggers), then defences (detection, sandbox, endpoint protection). Defensive throughout.

Test yourself

  1. What are the two independent questions that classify malware, and why is their independence the key idea?

The two questions are how the malware spreads (its propagation mechanism) and what it does (its payload). Their independence is the key idea because a piece of malware has both at once, so the families are not a flat parallel list but combinations: a trojan, which is a propagation mechanism, can carry a ransomware payload, and a worm, another propagation mechanism, can carry spyware. Holding the two questions apart prevents the confusion of treating propagation and payload as if they were alternatives.

  1. How do a virus, a worm and a trojan differ as propagation mechanisms?
munotes.in503

The Malware Families

A virus attaches itself to a host file and spreads when the user runs that host, so it requires user action and a host to live in. A worm self-propagates across networks without needing a user to do anything, which is why worms can spread explosively. A trojan does not spread on its own at all; it relies on deception, masquerading as legitimate or desirable software so that the user installs it. So the three differ in whether spreading needs a host and a user, happens automatically, or depends on tricking the user.

  1. Why is "is this malware a worm or ransomware?" a confused question?

Because the two words answer different questions: worm names how the malware spreads, self-propagating across networks, while ransomware names what it does, encrypting files for extortion. A single sample can be both, a worm that spreads itself and carries a ransomware payload, so treating them as mutually exclusive alternatives misunderstands the classification, much as asking whether a vehicle is a diesel or a truck confuses how it is powered with what it is for.

  1. How does the two-question map shape malware defence?

It maps onto two lines of defence. Defending against propagation aims to stop malware getting in and spreading, through patching so worms cannot exploit known flaws, user awareness so trojans do not deceive, segmentation so spread is contained, and controlling what may run. Defending against the payload aims to limit and detect the harm, through backups so ransomware encryption is survivable, least privilege so a payload can do less, and monitoring and detection so covert action is noticed. A complete defence addresses both lines.

  1. Why is the malware block taught entirely from the defender's side?

Because the course's purpose is defensive understanding, and understanding how malware behaves is exactly what enables a defender to recognise, detect and stop it, which is the block's aim. Writing or deploying malware is a serious offence under the IT Act, covering unauthorised access, damage and the introduction of malicious code, and is outside the course, so the block teaches what each family is, how it behaves, how it is detected, and how it is countered, consistent with the whole book's defensive register.

Contents This chapter on its own page

munotes.in504

Chapter One Hundred Ten

Viruses and Worms

Syllabus topic Module 2, "Malware Analysis and Threat Detection: types of malware (viruses, worms, ...), malware behaviour"

In one line

A virus attaches to a host file and spreads when the user runs the host, so it needs the user and spreads at human speed. A worm spreads itself across networks by exploiting flaws, needing no user, so it spreads at machine speed. The difference, needs-the-user versus spreads-itself, decides how each is stopped.

In examination wording: a virus is malware that attaches to a host program or file and propagates when the infected host is executed by a user, whereas a worm is malware that self-propagates across networks by exploiting vulnerabilities without requiring user action; the distinction in propagation determines the defences, user awareness and execution control for viruses, and patching and network segmentation for worms.

The virus: needs a host and a user

A virus is defined by how it spreads: it attaches itself to a host (a program or file), and it spreads when the user runs the infected host. Two things are essential, and both are examinable:

  • It needs a host to live in. A virus is not a standalone program; it embeds itself in something else, and it travels wherever that host travels (a shared file, a program copied between machines).
  • It needs the user to act. A virus spreads when someone runs the infected host, so its spread is gated by human action, which means it spreads at human speed and can be interrupted by user caution.

So a virus's behaviour is: attach to a host, wait to be run, and when run, execute its payload and attach itself to other hosts, spreading further. The dependence on the user is the defining limit, and it shapes the defence.

Defending against viruses follows from the definition:

  • Do not run untrusted hosts. User awareness (do not open or run unexpected files) directly interrupts the spread, because the virus needs the user to run the host.
  • Control what can run (allow only approved software), so an infected host cannot execute.
  • Anti-virus scanning to detect known viruses in files (the detection chapter's signature method historically began with exactly this).

The worm: spreads itself

A worm is defined by the opposite property: it spreads itself, across networks, by exploiting vulnerabilities, and it needs no user action at all. This single difference changes everything:

  • It is a standalone program, not attached to a host; it does not need something else to live in.
  • It needs no user. It finds other vulnerable machines over the network and infects them by exploiting a flaw, then those machines do the same, so it spreads at machine speed, which can be explosively fast, and no user caution interrupts it.

So a worm's behaviour is: run on an infected machine, scan the network for other vulnerable machines, exploit them to copy itself across, and repeat, growing exponentially without anyone doing anything. The historic worms that spread worldwide in hours were worms precisely because they needed no user, which is why worm outbreaks are a distinct and severe category.

munotes.in505

Viruses and Worms

Defending against worms follows from the definition, and is different from virus defence:

  • Patching. Because a worm spreads by exploiting vulnerabilities, keeping systems patched removes the flaws it uses, which is the single most important worm defence, and the reason the patch-management chapters matter here.
  • Network segmentation. Because a worm spreads across the network, segmenting the network (limiting what can talk to what) contains an outbreak, stopping a worm on one segment reaching others.
  • Blocking unnecessary network services, reducing the surface a worm can exploit.

User awareness, central to virus defence, does not help against a worm, because the worm needs no user; this contrast is the examinable heart of the chapter.

The contrast that governs everything

Placing them side by side, which is the chapter's point:

VirusWorm
Attaches to a host?Yes, needs a hostNo, standalone
Needs the user?Yes, spreads when the host is runNo, self-propagates
Speed of spreadHuman speedMachine speed, can be explosive
Spreads byThe user running the infected hostExploiting network vulnerabilities
Primary defenceUser awareness, execution controlPatching, segmentation

The one difference, needs-the-user versus spreads-itself, drives the whole table, including the defences, and a student who holds that difference can reconstruct everything else. It also explains why worms are treated as a more urgent outbreak risk: nothing human-paced gates them.

Modern malware often blends the two (using several propagation methods), but the two pure mechanisms and their contrast are the concepts to hold, and blended threats are understood as combinations of them.

A worked example, framed defensively

An analyst assesses two malware incidents and prescribes defences by propagation type, at concept level.

  • Incident one spread when users opened an infected document that carried the malware; machines whose users did not open it were unaffected. Classification: virus behaviour (needs the user, attached to a host). Defences: user awareness (do not open unexpected files), execution control, and anti-virus scanning. The spread is human-paced, so caution interrupts it.
  • Incident two spread to machines whose users did nothing, jumping across the network overnight to every unpatched machine. Classification: worm behaviour (self-propagating, exploiting a vulnerability). Defences: urgent patching of the exploited flaw, network segmentation to contain it, and blocking the service it used. User awareness is irrelevant here, because no user was involved.
  • The analyst notes that a blended threat could show both behaviours and would need both sets of defences.
munotes.in506

Viruses and Worms

The response is driven by the propagation type: the virus incident by user-facing defences, the worm incident by patching and segmentation, because the needs-the-user versus spreads-itself distinction determines what stops each. The analyst classifies and defends, and does not create or release either.

What beginners get wrong

  • Using "virus" for all malware. A virus is a specific propagation mechanism (attaches to a host, needs the user); worms, trojans and the rest are different, and the loose usage hides the distinctions that matter for defence.
  • Missing that a virus needs the user. Its spread is gated by someone running the infected host, so it moves at human speed and user caution interrupts it, unlike a worm.
  • Thinking user awareness stops worms. It does not; a worm needs no user, so patching and segmentation, not awareness, are its defences.
  • Underrating worm speed. Because worms self-propagate at machine speed, an outbreak can reach every unpatched machine in hours, which is why patching is urgent.
  • Forgetting that a virus needs a host. It is not standalone; it embeds in a program or file and travels with it, whereas a worm is a standalone program.
  • Overlooking blended threats. Modern malware may use several propagation methods at once and needs the defences for each; the pure mechanisms are the concepts, blends are combinations.

Quick revision

  • Virus: attaches to a host (program or file); spreads when the user runs the host; needs the user; human speed. Defence: user awareness, execution control, anti-virus.
  • Worm: standalone; self-propagates across networks by exploiting vulnerabilities; needs no user; machine speed, can be explosive. Defence: patching (removes the flaws it uses) and segmentation (contains spread); user awareness does not help.
  • The governing difference: needs-the-user (virus) versus spreads-itself (worm), which drives speed, mechanism and defence.
  • Modern malware often blends propagation methods; understand them as combinations of the two pure mechanisms.

Test yourself

  1. What defines a virus, and how does its dependence on the user shape its defence?

A virus is defined by attaching itself to a host program or file and spreading when the user runs the infected host, so it needs both a host to live in and a user to act. This dependence means it spreads at human speed and its spread is gated by user behaviour, so its defences are user-facing: user awareness not to run untrusted hosts, controlling what software may run so an infected host cannot execute, and anti-virus scanning to detect known viruses, all of which work precisely because the virus needs the user.

  1. What defines a worm, and why is it a more urgent outbreak risk than a virus?

A worm is a standalone program that self-propagates across networks by exploiting vulnerabilities, needing no user action. It is a more urgent outbreak risk because, needing no user, nothing human-paced gates its spread, so it moves at machine speed, scanning for and infecting vulnerable machines which then do the same, allowing an outbreak to reach every unpatched machine in hours. The historic worldwide worm outbreaks spread so fast exactly because they required no user.

munotes.in507

Viruses and Worms

  1. Why does user awareness defend against viruses but not against worms?

Because a virus needs the user to run the infected host, so a cautious user who does not open or run untrusted files interrupts the virus's spread, whereas a worm needs no user at all, propagating by exploiting network vulnerabilities automatically, so no amount of user caution affects it. This is why worm defence rests instead on patching, which removes the vulnerabilities the worm exploits, and on network segmentation, which contains its spread.

  1. Why is patching the single most important defence against worms?

Because a worm spreads by exploiting vulnerabilities in network-facing software, so keeping systems patched removes the very flaws the worm uses to copy itself across, cutting off its propagation at the source. Since a worm needs no user and spreads at machine speed, there is no human-paced control to fall back on, which makes promptly removing the exploited flaws through patching, together with segmentation to contain any spread, the decisive worm defence.

  1. What single difference between viruses and worms governs their speed, mechanism and defence, and how?

The difference is whether spreading needs the user (virus) or happens by itself (worm). It governs speed because a virus is gated by human action and so spreads at human speed while a worm spreads at machine speed; it governs mechanism because a virus attaches to a host run by the user while a worm exploits network vulnerabilities automatically; and it governs defence because a virus is countered by user awareness and execution control while a worm is countered by patching and segmentation, with user awareness useless against it. From that one difference the whole contrast follows.

Contents This chapter on its own page

munotes.in508

Chapter One Hundred Eleven

Trojans, Ransomware and Remote Access Tools

Syllabus topic Module 2, "Malware Analysis and Threat Detection: types of malware (... trojans, ransomware, ...), malware behaviour"

In one line

A trojan spreads by deception, pretending to be legitimate software so the user installs it; it is the delivery mechanism for most serious payloads. Ransomware encrypts the victim's files and demands payment, defended above all by backups. A remote access tool, legitimate in itself, becomes malware when used to give an attacker covert remote control; its defence is detecting the unexpected control channel.

In examination wording: a trojan is malware that masquerades as legitimate or desirable software to induce the user to install it; ransomware is a payload that encrypts the victim's data and demands payment for its release, mitigated principally by reliable offline backups; a remote access tool provides remote control of a system and constitutes malware when deployed without authorisation to give an attacker covert control, detected by monitoring for anomalous remote-access channels.

The trojan: deception as propagation

The malware-map chapter placed the trojan as a propagation mechanism, but a special one: it does not spread by attaching to hosts (virus) or by exploiting flaws (worm); it spreads by deception. The trojan (named for the wooden horse) pretends to be something the user wants, a useful program, a game, a document, a cracked application, and the user, deceived, installs it themselves, carrying it past the defences.

This makes the trojan the human-factor malware: it defeats technical controls by persuading the user to act, which is why it is the delivery mechanism for so many serious incidents. The user's own action, taken in good faith, installs the payload.

The trojan's importance is that it carries a payload. By itself, "trojan" says only how the malware arrived (by deception); what it does is the payload it carries, which is often one of the two this chapter covers next. So a typical serious incident is a trojan carrying ransomware or a trojan carrying a remote access tool: deception gets it in, and the payload does the harm.

Defending against trojans is about the deception:

  • User awareness, the central defence: only install software from trusted sources, be suspicious of unexpected or too-good-to-be-true programs, and verify what is being installed.
  • Controlling what can run (allow only approved software), so even a deceived user cannot install an unapproved program.
  • Least privilege, so that if a trojan is installed, it runs with limited rights and its payload can do less.

Ransomware: encryption as extortion

Ransomware is the payload that encrypts the victim's files (making them unreadable) and demands a payment (a ransom) for the key to decrypt them. Its behaviour, which a defender must recognise, is: once running, it encrypts documents and data across the machine and often across reachable network shares, then displays a demand. The harm is loss of access to the data, which for an organisation can halt operations.

munotes.in509

Trojans, Ransomware and Remote Access Tools

Ransomware is important because it turns the encryption the book has taught as a defence into a weapon: the same strong encryption that protects data, used against the owner, locks them out, and if the encryption is done correctly the files cannot be recovered without the key. This is why ransomware is so damaging and why the defence is not "break the encryption" (which is infeasible if done correctly) but preparation.

Defending against ransomware is the clearest case of preparation over cure:

  • Backups, above all. Reliable, regularly-tested backups that are offline or otherwise out of the ransomware's reach mean that if files are encrypted, they can be restored, defeating the extortion. This is the single most important ransomware defence, because it makes the encryption survivable. Backups that the ransomware can also encrypt (always-connected) do not count, so offline or immutable backups matter.
  • Stopping the delivery: since ransomware usually arrives by trojan or by exploiting a flaw, the trojan and worm defences (awareness, execution control, patching) prevent it getting in.
  • Least privilege and segmentation, so that ransomware which does run reaches fewer files and cannot spread across the network.
  • Not relying on paying, because payment funds crime, may not restore the data, and marks the victim as willing to pay; the recovery plan is backups, not ransom.

The examinable point: ransomware weaponises correct encryption, so it cannot be reversed by breaking the encryption; the defence is backups (out of reach) plus preventing delivery and limiting spread.

Remote access tools: control as payload

A remote access tool gives someone remote control of a computer, seeing the screen, running programs, accessing files, as if sitting at it. Remote access tools are legitimate and common (IT support and remote work rely on them), so the tool itself is not malware. It becomes malware by how it is used: deployed without authorisation, covertly, to give an attacker control of a victim's machine.

This is the clearest instance of the dual-use theme the book has returned to: the same capability is administration when authorised and covert and attacker-controlled and malware when not. The malicious remote access tool (often delivered by a trojan) gives the attacker an ongoing control channel: they can operate the machine, steal data, install more malware, and use it as a foothold.

Defending against malicious remote access is about the control channel, since the tool itself may be ordinary:

  • Detecting the unexpected channel. Because the tool may look legitimate, the defence is noticing the unauthorised remote-access connection: an unexpected program communicating out, a remote session no one authorised, unusual outbound traffic (the monitoring and network-detection chapters). What marks it as malicious is that it is unauthorised, so authorisation and expectation are the test.
  • Controlling what can run and communicate, so an unapproved remote access tool cannot be installed or cannot reach the network.
  • Least privilege and segmentation, limiting what a controlled machine can reach.
  • The trojan defences, since the tool is usually delivered by deception.
munotes.in510

Trojans, Ransomware and Remote Access Tools

How the three fit together

The three belong in one chapter because they describe how most serious incidents actually unfold: a trojan (deception) delivers a payload that is either ransomware (extort) or a remote access tool (control). Propagation and payload, the map's two questions, made concrete. And the defences layer accordingly: stop the deception (awareness, execution control), prepare for the payload (backups for ransomware, monitoring for remote control), and limit both (least privilege, segmentation). A student who sees the trojan-plus-payload pattern understands the shape of real incidents.

A worked example, framed defensively

An analyst reconstructs an incident and prescribes defences, at concept level, on the organisation's systems.

  • The malware arrived as a cracked application an employee downloaded and installed. Propagation: trojan (deception). Preventive lesson: user awareness and allowing only approved software.
  • Its first payload was a remote access capability giving an external party covert control, used to explore the network. Payload: malicious remote access. Detection lesson: the unauthorised outbound control channel should have been caught by monitoring; defence is detecting unexpected remote access and segmentation to limit reach.
  • Its second stage encrypted files and demanded payment. Payload: ransomware. Recovery: restore from offline backups (available and tested), so the extortion failed; the organisation did not pay.
  • The analyst's recommendations: execution control and awareness (stop the trojan), monitoring for anomalous remote-access channels (catch the control), offline backups and least privilege and segmentation (survive and limit the ransomware).

The reconstruction follows the trojan-plus-payload pattern, and the defences are preparation and detection: backups made the ransomware survivable and monitoring is the answer to covert control. The analyst investigates and defends, and does not build or operate any of the malware.

What beginners get wrong

  • Thinking a trojan is defined by what it does. It is defined by how it arrives, by deception; what it does is the payload it carries, often ransomware or a remote access tool.
  • Believing ransomware can be defeated by breaking the encryption. If the encryption is done correctly it cannot be reversed; the defence is offline backups that make the encryption survivable, plus preventing delivery.
  • Counting always-connected backups as protection. Ransomware can encrypt reachable backups too; only backups out of its reach (offline or immutable) defeat it.
  • Treating remote access tools as inherently malware. They are legitimate and common; what makes one malware is unauthorised, covert use, so authorisation is the test, and detection targets the unexpected channel.
  • Planning to pay the ransom. Payment funds crime, may not restore data, and marks the victim; the recovery plan is backups.
  • Missing the trojan-plus-payload pattern. Most serious incidents are deception delivering a payload; seeing the pattern explains the layered defence.
munotes.in511

Trojans, Ransomware and Remote Access Tools

Quick revision

  • Trojan: propagation by deception; pretends to be legitimate software so the user installs it; the human-factor malware and the usual delivery for payloads. Defence: user awareness, execution control, least privilege.
  • Ransomware (payload): encrypts files and demands payment; weaponises correct encryption, so it cannot be reversed by breaking it. Defence: offline/immutable backups above all (make it survivable), prevent delivery, limit spread; do not rely on paying.
  • Remote access tool used maliciously (payload): covert remote control; the tool is legitimate, the unauthorised use is the malware (dual-use). Defence: detect the unexpected control channel (monitoring), execution/communication control, least privilege, segmentation.
  • The pattern of real incidents: a trojan delivers a payload (ransomware or remote control); defences layer as stop-deception, prepare-for-payload, limit-both.

Test yourself

  1. What defines a trojan, and why is it the delivery mechanism for so many serious incidents?

A trojan is defined by its propagation through deception: it masquerades as legitimate or desirable software so that the user, deceived, installs it themselves, carrying it past technical defences. It is the delivery mechanism for so many serious incidents because it exploits the human factor, persuading the user to act rather than defeating a control technically, and because by itself it only names how the malware arrived, it typically carries a payload such as ransomware or a remote access tool, so deception gets the malware in and the payload does the harm.

  1. Why can ransomware not be defeated by breaking its encryption, and what is the principal defence?

Because ransomware uses strong, correctly-implemented encryption to lock the victim's files, and correct encryption cannot feasibly be reversed without the key, which is the same property that makes encryption a trustworthy defence when used legitimately. The principal defence is therefore preparation rather than cure: reliable, regularly-tested backups kept offline or otherwise out of the ransomware's reach, so that encrypted files can be restored and the extortion fails, making the encryption survivable without paying.

  1. Why do always-connected backups fail against ransomware, and what kind of backups work?

Always-connected backups fail because ransomware encrypts data across the machine and often across every reachable network share and connected drive, so backups it can reach are encrypted along with the originals and become useless for recovery. Backups that work are those kept out of the ransomware's reach, offline or otherwise disconnected, or immutable so they cannot be altered or encrypted, because only backups the ransomware cannot touch remain available to restore from after an attack.

munotes.in512

Trojans, Ransomware and Remote Access Tools

  1. When is a remote access tool malware, and how does that shape its detection?

A remote access tool is malware not by its nature, since such tools are legitimate and widely used for IT support and remote work, but by its use: when deployed without authorisation and covertly to give an attacker control of a victim's machine. Because the tool itself may look ordinary, detection cannot rely on recognising a malicious program and instead targets the unauthorised control channel, monitoring for an unexpected remote session, a program communicating out that no one authorised, or unusual outbound traffic, with authorisation and expectation as the test of whether the access is legitimate.

  1. How do the trojan, ransomware and remote access tool fit the two-question malware map, and how do their defences layer?

They fit the map as a propagation mechanism delivering a payload: the trojan is propagation by deception, and ransomware and malicious remote access are payloads, so a typical serious incident is a trojan carrying one of those payloads. The defences layer accordingly: stop the deception with user awareness and execution control, prepare for the payload with offline backups against ransomware and monitoring against covert control, and limit both with least privilege and segmentation, so that classifying an incident on the map directly yields its layered defence.

Contents This chapter on its own page

munotes.in513

Chapter One Hundred Twelve

Keyloggers and Spyware: the Architecture

Syllabus topic Module 2, "Malware Analysis and Threat Detection: types of malware (... spyware), malware behaviour"

In one line

Spyware secretly gathers information about the user; a keylogger is the spyware that records keystrokes (capturing passwords and messages as they are typed). Understood defensively, every such payload must capture the information, store it, and exfiltrate it to the attacker, and each of those three stages is where a defender detects and stops it.

In examination wording: spyware is malware that covertly collects information about a user or system and transmits it to a third party; a keylogger is spyware that records keystrokes to capture typed credentials and communications; defensively, such payloads follow a capture-store-exfiltrate pattern, and detection targets the anomalous exfiltration of data and the presence of the covert program.

Why understand the architecture, defensively

MU asks for "malware behaviour", and for spyware the useful behaviour to understand is the shape every covert-information payload must have, because that shape is where a defender catches it. This chapter describes that shape, the capture, store, exfiltrate pattern, strictly as a detection map: knowing the three stages a spyware program must perform tells a defender the three places to look for it. It is not a guide to building one; it is the structure a defender uses to recognise and stop one, which is exactly the defensive value MU intends by "behaviour".

The reason this works: spyware's purpose is to get the user's information to the attacker. That purpose forces a structure, and the structure has observable points. A defender who knows the structure knows what to monitor.

Spyware and the keylogger

Spyware is the general payload: software that covertly gathers information about the user or the system, browsing habits, files, credentials, screenshots, and reports it to a third party, all without the user's knowledge. Its defining properties are that it is covert (hidden from the user) and that it gathers and reports information (rather than encrypting or destroying).

A keylogger is the specific and important case: spyware that records what the user types. It is important because typed keystrokes include the most sensitive things, passwords as they are entered, messages, card numbers, before any encryption protects them, so a keylogger captures secrets at the one moment they are in the clear. This connects to the password chapters: a keylogger defeats even a strong password, because it captures the password as it is typed, which is why it is a serious threat and why defences like multi-factor authentication (something beyond the typed password) matter, since a captured password alone is then not enough.

The three stages, as detection points

Every covert-information payload, to fulfil its purpose, must do three things, and the defensive point is that each is a detection opportunity:

  1. Capture. It must obtain the information, recording keystrokes, taking screenshots, reading files. Detection point: the act of capturing often requires the program to interpose itself in a way that monitoring and endpoint protection can recognise as anomalous (a program watching all keystrokes is unusual and detectable), and the covert program's mere presence can be found by scanning.
  2. Store. It must hold the captured information, at least briefly, before sending it. Detection point: hidden accumulation of captured data can be found by inspection, and the storage is a forensic artefact after the fact.
  3. Exfiltrate. It must send the information to the attacker, which means communicating out of the machine or network. Detection point, and the strongest: the exfiltration is a network event, so monitoring outbound traffic (the network-detection chapters) can catch data leaving to an unexpected destination. This is the most reliable detection, because the payload's whole purpose requires it to communicate out, and it cannot avoid this stage.
munotes.in514

Keyloggers and Spyware: the Architecture

The examinable insight: the exfiltration stage is the payload's necessary weakness. However covert the capture and storage, the information must reach the attacker, so it must leave the machine, and that departure is detectable by network monitoring. A defender who watches for anomalous outbound data has a detection that spyware cannot fully evade, because evading it would defeat the spyware's purpose.

Defending against spyware and keyloggers

The defences follow from the stages and from the delivery:

  • Prevent installation (the delivery is usually a trojan or an exploit): user awareness, execution control, patching, least privilege, the defences already built.
  • Detect the program: endpoint protection and scanning find known spyware and recognise the anomalous behaviour of capture (the detection chapter's methods).
  • Detect the exfiltration: network monitoring for unexpected outbound connections and unusual data transfers, the stage the payload cannot skip.
  • Limit the value of what is captured: multi-factor authentication, so a captured password alone is insufficient; and not entering the most sensitive data on untrusted machines.
  • Least privilege, limiting what spyware can read.

The layered point: prevent delivery, detect the program and its capture behaviour, and above all detect the exfiltration, while multi-factor authentication limits the damage of what a keylogger captures.

A worked example, framed defensively

An analyst investigates a suspected data-theft incident, using the capture-store-exfiltrate map to guide detection, on the organisation's systems.

  • Monitoring flagged an unexpected outbound connection sending data to an unfamiliar destination at regular intervals. The exfiltration stage, the payload's necessary weakness, is what surfaced the incident, illustrating why network monitoring is the strongest detection.
  • Investigation found a covert program recording keystrokes (a keylogger), delivered earlier by a trojan. The capture stage: the program interposed to record typing, and its presence and behaviour were then identifiable.
  • A hidden store of captured keystrokes was found on the machine. The storage stage, a forensic artefact confirming what was taken.
  • Response and lessons: the entry was a trojan (so awareness and execution control), the capture was detectable behaviour (so endpoint protection), the exfiltration was the catch (so continued network monitoring), and because passwords were captured, multi-factor authentication limited the damage and captured passwords were reset.
munotes.in515

Keyloggers and Spyware: the Architecture

The investigation used the three-stage map as a detection guide, catching the incident at the exfiltration stage the payload could not avoid. The analyst detects, investigates and defends, and does not build or deploy the spyware.

What beginners get wrong

  • Thinking spyware is defined by damage. It is covert information gathering and reporting, not destruction; its harm is the theft and exposure of information.
  • Underrating the keylogger. It captures passwords and messages as they are typed, before encryption protects them, so it defeats even a strong password, which is why multi-factor authentication matters.
  • Missing that exfiltration is unavoidable. The payload must send the information to the attacker, so it must communicate out, making network monitoring the detection it cannot fully evade.
  • Treating the architecture as a build guide. The three stages are a detection map: they tell a defender the three places to look, which is the defensive value of understanding the behaviour.
  • Relying only on anti-virus. Detecting the program matters, but detecting the exfiltration (network monitoring) is the stronger, evasion-resistant catch, and preventing delivery stops it earlier.
  • Forgetting to limit captured value. Multi-factor authentication and not entering secrets on untrusted machines reduce the damage even when capture occurs.

Quick revision

  • Spyware: covert software that gathers information and reports it to a third party. Keylogger: spyware that records keystrokes, capturing passwords and messages as typed, before encryption, defeating even a strong password (hence multi-factor authentication).
  • Understood defensively, every such payload must capture, store, and exfiltrate, and each stage is a detection point.
  • Exfiltration is the necessary weakness: the information must reach the attacker, so it must leave the machine, and network monitoring of outbound traffic catches it, the evasion-resistant detection.
  • Defence layers: prevent delivery (trojan/exploit defences), detect the program and capture behaviour (endpoint protection), detect exfiltration (network monitoring), limit captured value (multi-factor authentication, least privilege).

Test yourself

  1. What is spyware, what is a keylogger, and why is a keylogger especially dangerous?

Spyware is malware that covertly gathers information about the user or system, such as browsing habits, files, or credentials, and reports it to a third party without the user's knowledge, defined by being hidden and by gathering and reporting rather than destroying. A keylogger is the specific spyware that records what the user types, and it is especially dangerous because typed keystrokes include passwords, messages and card numbers at the one moment they are in the clear, before any encryption protects them, so a keylogger captures secrets directly and defeats even a strong password.

munotes.in516

Keyloggers and Spyware: the Architecture

  1. What three stages must every covert-information payload perform, and why is each a detection point?

It must capture the information, store it at least briefly, and exfiltrate it to the attacker. Capture is a detection point because interposing to record keystrokes or screens is anomalous behaviour that endpoint protection can recognise, and the covert program can be found by scanning; storage is a detection point because hidden accumulated data can be found by inspection and is a forensic artefact; and exfiltration is a detection point, the strongest, because sending the data out is a network event that monitoring of outbound traffic can catch.

  1. Why is the exfiltration stage described as the payload's necessary weakness?

Because the payload's whole purpose is to get the user's information to the attacker, so however covert the capture and storage, the information must ultimately leave the machine and travel to the attacker, which is an observable network event. The payload cannot skip this stage without failing its purpose, so a defender who monitors for anomalous outbound data has a detection that spyware cannot fully evade, since evading it would mean never delivering the stolen information.

  1. How does multi-factor authentication limit the damage of a keylogger, and why is that necessary?

Multi-factor authentication requires something beyond the typed password, such as a code from a separate device or a hardware key, so that a password captured by a keylogger is not by itself enough to gain access. It is necessary because a keylogger captures the password as it is typed, before encryption, which defeats the password no matter how strong it is, so the password alone can no longer be trusted; requiring an additional factor that the keylogger did not capture preserves security despite the captured password.

  1. Why is understanding the capture-store-exfiltrate architecture a defensive skill rather than a construction guide?

Because knowing the three stages a covert-information payload must perform tells a defender the three places to look for it: the anomalous capture behaviour and the covert program, the hidden storage, and above all the unavoidable exfiltration over the network. The architecture is used as a detection map that directs monitoring and investigation to where the payload is observable, which is the defensive value MU intends by asking for malware behaviour, and it describes what to recognise and stop rather than anything to build.

Contents This chapter on its own page

munotes.in517

Chapter One Hundred Thirteen

Detection: Signature, Heuristic and Behavioural

Syllabus topic Module 2, "Malware Analysis and Threat Detection: ... threat detection"

In one line

Malware is detected three ways, each answering the last one's gap. Signature detection matches known malware by a fingerprint (exact, but blind to the new). Heuristic detection flags code that looks like malware (catches variants, risks false alarms). Behavioural detection watches what a program does at run time and flags malicious actions (catches never-seen malware, the strongest against the unknown).

In examination wording: signature-based detection identifies malware by matching a known pattern or hash, which is precise but cannot detect previously unseen malware; heuristic detection identifies likely malware by suspicious characteristics or similarity to known families, detecting variants at the cost of false positives; behavioural detection observes a program's actions during execution and flags malicious behaviour, enabling detection of novel and zero-day malware.

The progression that structures the chapter

The three methods are best learned as a progression, because each exists to fix the previous one's weakness, and that logic is the examinable heart:

  1. Signature detection is precise but only catches known malware.
  2. Heuristic detection was added to catch malware similar to the known (variants), fixing signatures' blindness to new-but-related samples, at the cost of false alarms.
  3. Behavioural detection was added to catch the entirely new by what it does, fixing both previous methods' reliance on recognising the code, at the cost of needing to run or closely watch the program.

A student who presents the three as answers to a growing problem, how to catch malware that has never been seen before, understands them as MU intends, not as three unrelated techniques.

Signature detection: matching the known

Signature detection identifies malware by a signature, a distinctive pattern or fingerprint (historically a sequence of bytes, or a hash) that uniquely identifies a known malware sample. The detector holds a database of signatures and scans files for matches; a match means that known malware is present.

Its properties:

  • Precise and reliable for the known. A signature match is near-certain: this is that malware. False positives are low, because the signature is specific.
  • Blind to the unknown. It can only detect malware whose signature is already in the database, so a brand-new malware, or a modified one whose pattern differs, is missed until its signature is created and distributed. This is the fundamental limit.
  • Requires constant updates. The signature database must be continually updated as new malware appears, which is why anti-virus updates matter, and even then there is a window between a new malware appearing and its signature being available, during which signature detection cannot see it.

So signature detection is the accurate but backward-looking method: excellent for the vast body of known malware, useless against the genuinely new. Its weakness, blindness to the unknown, is what the other methods address.

munotes.in518

Detection: Signature, Heuristic and Behavioural

Heuristic detection: catching the similar

Heuristic detection identifies likely malware by suspicious characteristics or similarity to known malware, rather than by an exact signature. Instead of asking "is this exactly a known sample?", it asks "does this look like malware?", examining the code for traits common to malware or for resemblance to known families.

Its properties:

  • Catches variants and the similar-to-known. Because it does not need an exact match, it can flag a modified version of known malware, or a new sample sharing malware-like traits, which signatures miss. This closes part of signatures' blindness.
  • Risks false positives. Judging by resemblance rather than certainty, it can flag legitimate programs that happen to share suspicious traits, so heuristic detection produces false alarms that signature detection largely avoids. Tuning the sensitivity trades detection against false positives.
  • Still fundamentally about inspecting the code (what it looks like), so a sufficiently different or well-disguised new malware can still evade it.

So heuristic detection extends reach to the similar-to-known at the cost of certainty, and it is the middle method: broader than signatures, less precise, and still ultimately looking at the code rather than the behaviour.

Behavioural detection: catching the unknown by what it does

Behavioural detection takes the decisive different approach: instead of examining what a program looks like, it watches what a program does while it runs, and flags malicious behaviour, regardless of whether the program has ever been seen before. It asks "is this program acting like malware?", watching for actions such as rapidly encrypting many files (ransomware), recording keystrokes (a keylogger), or unexpected outbound connections (exfiltration).

Its properties, and why it is the answer to the unknown:

  • Catches never-seen malware. Because it judges by behaviour, not by recognising the code, it can detect brand-new, zero-day malware that has no signature and evades heuristics, as long as the malware does something recognisably malicious, which by definition it must to cause harm. This is the crucial strength, closing the window that signatures leave open.
  • Detects by the harmful action itself, which ties directly to the earlier chapters: the spyware architecture's exfiltration stage, ransomware's encryption behaviour, the keylogger's capture, all are behaviours a behavioural detector watches for, which is why understanding malware behaviour is a detection skill.
  • Costs and limits. It generally needs to observe the program running (or closely monitor its actions), which is more resource-intensive, and it can also produce false positives when legitimate programs do things that resemble malicious behaviour. And catching malware by its behaviour may mean catching it as it begins to act, so it is paired with the ability to stop and contain quickly.

So behavioural detection is the strongest against the unknown, because harmful malware must act, and acting is what it detects, at the cost of running the program and watching closely, which is exactly what the sandbox (next chapter) provides safely.

munotes.in519

Detection: Signature, Heuristic and Behavioural

The three together

The methods are complementary and used together, which is the practical conclusion:

  • Signatures handle the huge volume of known malware cheaply and precisely.
  • Heuristics extend to variants and the similar, catching modified known malware.
  • Behavioural detection catches the genuinely new by what it does, closing the zero-day gap.

Modern endpoint protection (the chapter after next) combines all three, because none suffices alone: signatures miss the new, heuristics miss the well-disguised, and behavioural detection is costlier and catches malware only as it acts. Layered, they cover known, similar and novel threats, which is the defence in depth the block has taught throughout.

A worked example, framed defensively

A security team evaluates why a novel malware sample was, and was not, caught by their layers, at concept level.

  • The sample was brand-new, so signature detection missed it: no signature existed yet, the expected blindness to the unknown.
  • It shared some traits with a known family, so heuristic detection flagged it as suspicious, illustrating heuristics catching the similar-to-known, though the team notes heuristics also raised some false positives on legitimate software that week.
  • When run in the protected environment, it began encrypting files rapidly, so behavioural detection identified it as ransomware by its actions and it was contained, illustrating behavioural detection catching the novel by what it does, tied to ransomware's known behaviour.
  • Conclusion: the layers are complementary, signatures for the known, heuristics for the similar, behavioural for the novel, and the novel sample was ultimately caught by its behaviour, confirming why all three are run together.

The evaluation shows each method's role and limit, and why they are layered. The team detects and analyses; nothing offensive is built.

What beginners get wrong

  • Thinking signature detection is enough. It is precise but blind to anything not already in its database, so it misses new and modified malware until a signature exists; the window it leaves open is why other methods are needed.
  • Confusing heuristic and behavioural detection. Heuristic inspects what the code looks like (similarity, suspicious traits); behavioural watches what the program does when it runs. Looking-like versus doing is the distinction.
  • Believing behavioural detection has no cost. It generally needs to run or closely watch the program and can raise false positives, and it may catch malware only as it starts to act, so it is paired with rapid containment.
  • Missing why understanding behaviour aids detection. Behavioural detection watches for exactly the actions the malware chapters described (encryption, keystroke capture, exfiltration), so knowing malware behaviour is a detection skill.
  • Treating the methods as competitors. They are complementary and layered; each covers a gap the others leave, which is why endpoint protection uses all three.
  • Ignoring false positives. Heuristic and behavioural detection trade some false alarms for catching the unknown; tuning balances detection against disruption.
munotes.in520

Detection: Signature, Heuristic and Behavioural

Quick revision

  • Signature: matches a known fingerprint (pattern/hash). Precise, low false positives, but blind to the unknown and needs constant updates; a window exists before a new signature is available.
  • Heuristic: flags code that looks like malware (suspicious traits, similarity to known families). Catches variants, at the cost of false positives; still inspects the code.
  • Behavioural: watches what a program does at run time and flags malicious actions (encryption, keystroke capture, exfiltration). Catches never-seen/zero-day malware because harmful malware must act; costs: needs to run/watch the program, some false positives, catches it as it acts (so pair with containment).
  • Used together: signatures (known), heuristics (similar), behavioural (novel); none suffices alone, so endpoint protection layers all three.

Test yourself

  1. How does signature detection work, and what is its fundamental limit?

Signature detection identifies malware by matching it against a database of signatures, distinctive patterns or hashes that uniquely identify known malware samples, so a match near-certainly means that known malware is present, with low false positives. Its fundamental limit is that it can only detect malware whose signature is already in the database, so a brand-new sample, or a modified one whose pattern differs, is missed until a signature is created and distributed, leaving a window during which signature detection is blind to the new threat.

  1. How does heuristic detection extend beyond signatures, and what does it cost?

Heuristic detection identifies likely malware by suspicious characteristics or similarity to known families rather than by an exact match, so it can flag modified versions of known malware and new samples sharing malware-like traits that signatures miss, closing part of the blindness to the unknown. It costs certainty: judging by resemblance, it can flag legitimate programs that happen to share suspicious traits, producing false positives that precise signature matching largely avoids, so its sensitivity must be tuned to balance detection against false alarms.

  1. What makes behavioural detection able to catch never-seen malware?

Behavioural detection watches what a program does while it runs and flags malicious actions rather than recognising the code, so it does not depend on having seen the malware before. Because any malware must perform some harmful action to cause harm, encrypting files, recording keystrokes, or sending data out, behavioural detection can identify even brand-new, zero-day malware by those actions, closing the window that signature and heuristic detection leave open for threats whose code is unrecognised.

munotes.in521

Detection: Signature, Heuristic and Behavioural

  1. Why does understanding malware behaviour, from the earlier chapters, directly support detection?

Because behavioural detection works by watching for exactly the actions those chapters described: ransomware rapidly encrypting many files, a keylogger recording keystrokes, spyware exfiltrating data over the network. Knowing how each malware family behaves tells a defender and a detector which actions signal which threat, so the study of malware behaviour is not academic but is the basis on which behavioural detection recognises malicious programs by what they do, including ones never seen before.

  1. Why are the three detection methods used together rather than one being chosen?

Because each has a gap the others cover: signatures are precise but blind to the unknown, heuristics catch the similar-to-known but miss well-disguised novel malware and raise false positives, and behavioural detection catches the genuinely new by its actions but is more costly, may catch malware only as it acts, and also risks false positives. Layering them lets signatures handle the large volume of known malware cheaply, heuristics catch variants, and behavioural detection close the zero-day gap, giving defence in depth across known, similar and novel threats.

Contents This chapter on its own page

munotes.in522

Chapter One Hundred Fourteen

Safe Analysis: the Sandbox

Syllabus topic Module 2, "Malware Analysis and Threat Detection: ... threat detection"

In one line

A sandbox is an isolated, disposable environment (typically a virtual machine, cut off from the real network and data) where a suspect program can be run and observed safely. It makes behavioural analysis possible without risk: the malware acts, the analyst watches, and afterwards the environment is discarded, so nothing real is harmed.

In examination wording: a sandbox is a controlled, isolated execution environment, commonly implemented with virtual machines separated from production systems and networks, in which suspect software is executed so that its behaviour can be observed safely; it enables dynamic and behavioural malware analysis while containing any harm within the disposable environment.

Why a sandbox is needed

The previous chapter established that behavioural detection, the method that catches never-seen malware, works by watching what a program does when it runs. But running suspected malware is exactly what a defender must never do carelessly, because if it is malware, running it causes the harm, encrypting files, spreading, exfiltrating. So there is a tension: to analyse behaviour you must run the program, but running it is dangerous.

The sandbox resolves the tension. It provides a place to run the suspect program where its actions cannot reach anything real, so the analyst can observe the behaviour (satisfying behavioural analysis) while any harm is contained (satisfying safety). The sandbox is therefore the enabling technology for behavioural detection and for responsible malware analysis, and it embodies the book's containment principle applied to the analyst's own work.

What makes an environment a sandbox

A sandbox is defined by isolation, and the examinable content is what must be isolated:

  • Isolated from real data. The environment contains no real or valuable files, so malware that encrypts or steals finds nothing of worth; the data is disposable.
  • Isolated from the real network. The environment is cut off from the production network (and often from the internet, or given only a carefully controlled and monitored network), so malware cannot spread to real machines or exfiltrate to the attacker, and any network behaviour it attempts is observed rather than allowed to reach real targets.
  • Disposable. The environment can be destroyed and recreated cleanly after analysis, so whatever the malware did to it does not persist; the analyst reverts to a clean state for the next sample. Virtual machines make this practical: a snapshot is taken, the malware is run, and the machine is reverted.
  • Instrumented. The environment records what the program does, the files it touches, the network connections it attempts, the changes it makes, so the analyst can study the behaviour, which is the point of running it.

Put together: a sandbox is a disposable, isolated, instrumented environment, usually a virtual machine, where the suspect runs cut off from anything real while its behaviour is recorded. Those four properties are the examinable definition.

munotes.in523

Safe Analysis: the Sandbox

The isolation discipline

The chapter states the discipline plainly, because it is where careless analysis becomes dangerous: the isolation must be real and complete. A sandbox that is not properly isolated is worse than none, because it invites running malware under a false sense of safety. So:

  • The sandbox must genuinely be cut off from real data and the real network; a "sandbox" still connected to the production network or holding real files does not contain the harm.
  • The analyst must assume the program is malware and may try to escape or to detect that it is being watched (some malware behaves differently, or does nothing, when it detects a sandbox, precisely to evade analysis), so the isolation cannot depend on the malware cooperating.
  • After analysis, the environment is discarded and rebuilt clean, never reused in a way that could carry contamination forward.
  • Malware analysis is done only by those authorised to do it, on samples they are authorised to handle, in a properly isolated environment; this is the responsible practice the course teaches.

The examinable point: the sandbox's value is entirely in its isolation, so the discipline is to make the isolation real, assume the malware is hostile and may try to escape or hide, and discard the environment afterwards.

The sandbox and behavioural detection together

The sandbox and behavioural detection are two halves of one idea, which is worth stating: behavioural detection asks "what does this program do?", and the sandbox is the safe place to find out. Automated systems combine them, running suspect files automatically in sandboxes and applying behavioural detection to what they do, which is how modern systems evaluate unknown attachments and downloads before delivering them: the file is detonated in a sandbox, its behaviour observed, and if it acts maliciously it is blocked. So the sandbox is not only a manual analyst's tool but a component of automated defence, and it is what makes catching zero-day malware by behaviour practical at scale.

A worked example, framed defensively

An analyst receives a suspicious email attachment to assess, and follows safe-analysis practice, at concept level.

  • The analyst does not open the attachment on their real workstation, because if it is malware, opening it there causes the harm. Instead they use a sandbox: an isolated virtual machine with no real data, cut off from the production network, with a clean snapshot taken.
  • Inside the sandbox, the attachment is run and observed. It attempts to encrypt files and connect out to an unfamiliar address. Because the environment is isolated, the encryption hits only disposable files and the connection does not reach the real attacker or spread, while the instrumentation records both behaviours.
  • Behavioural analysis concludes it is ransomware with an exfiltration component (tying to the earlier chapters), and the indicators (the destination it tried to reach, the files it targeted) are extracted to defend the real network.
  • The analyst reverts the sandbox to the clean snapshot, discarding whatever the malware did, and notes the sample tried to check whether it was in a sandbox, so the isolation had to be robust.
  • The findings, that the sample is ransomware and its indicators, are used to block it across the organisation.
munotes.in524

Safe Analysis: the Sandbox

The analysis was done safely because the sandbox contained the harm while revealing the behaviour, and the environment was discarded afterwards. The analyst studies the malware to defend against it, in isolation, and does not run it anywhere it could cause real harm.

What beginners get wrong

  • Running suspect programs on a real machine. If it is malware, running it causes the harm; suspect programs are run only in an isolated sandbox, never on a real workstation or network.
  • Thinking any virtual machine is a sandbox. It is a sandbox only if it is genuinely isolated from real data and the real network, disposable, and instrumented; a VM still connected to production does not contain the harm.
  • Assuming malware cooperates. Some malware detects sandboxes and behaves differently or does nothing to evade analysis, and some tries to escape, so the isolation must not depend on the malware behaving.
  • Reusing a contaminated environment. After analysis the environment is discarded and rebuilt clean, so contamination is not carried forward.
  • Separating the sandbox from behavioural detection. They are two halves of one idea: behavioural detection asks what a program does, and the sandbox is the safe place to find out, combined in automated defence.
  • Forgetting authorisation. Malware analysis is done by those authorised, on samples they may handle, in proper isolation; it is responsible practice, not casual experimentation.

Quick revision

  • A sandbox is a disposable, isolated, instrumented environment (usually a virtual machine) where a suspect program is run and observed safely.
  • It resolves the tension in behavioural analysis: you must run the program to see its behaviour, but running malware is dangerous; the sandbox lets it act while containing the harm.
  • Four properties: isolated from real data, isolated from the real network, disposable (revert to clean), instrumented (records what the program does).
  • Isolation discipline: make the isolation real and complete, assume the malware is hostile and may try to escape or detect the sandbox, discard and rebuild afterwards, and analyse only when authorised.
  • With behavioural detection: automated systems detonate suspect files in sandboxes and apply behavioural detection, which is how zero-day malware is caught by behaviour at scale.
munotes.in525

Safe Analysis: the Sandbox

Test yourself

  1. What tension in behavioural analysis does a sandbox resolve, and how?

Behavioural analysis must run a program to observe what it does, but running suspected malware is dangerous because, if it is malware, running it causes the harm it is designed to do. The sandbox resolves this by providing an isolated, disposable environment where the suspect program's actions cannot reach anything real, so the analyst can observe the behaviour while any harm is contained within the environment, satisfying both the need to see the behaviour and the need for safety.

  1. What four properties define a sandbox?

It is isolated from real data, so malware that encrypts or steals finds nothing of value; isolated from the real network, so malware cannot spread to real machines or exfiltrate to an attacker, with any network behaviour observed rather than allowed through; disposable, so the environment can be destroyed and recreated cleanly after analysis, reverting whatever the malware did; and instrumented, so it records what the program does, the files it touches and the connections it attempts, which is the point of running it. Together these make it a disposable, isolated, instrumented environment, usually a virtual machine.

  1. Why must the isolation be real and complete, and what must the analyst assume about the malware?

Because the sandbox's entire value is its isolation, so a sandbox that is not properly isolated is worse than none, since it invites running malware under a false sense of safety while the harm can still reach real data or the real network. The analyst must assume the program is malware and hostile, that it may try to escape the environment, and that it may detect it is in a sandbox and behave differently or do nothing to evade analysis, so the isolation cannot depend on the malware cooperating and must be robust against attempts to escape or detect it.

  1. Why is the environment discarded and rebuilt after analysis?

Because running the malware may have changed the environment in ways that persist, installing components, altering settings, or leaving contamination, so reusing it risks carrying that contamination into the next analysis or drawing wrong conclusions. Discarding the environment and reverting to a clean snapshot ensures each sample is analysed in a known-clean state and that whatever the malware did does not persist, which virtual-machine snapshots make quick and practical.

  1. How do the sandbox and behavioural detection combine in automated defence?

They are two halves of one idea: behavioural detection asks what a program does, and the sandbox is the safe place to find out. Automated systems combine them by detonating suspect files, such as unknown email attachments or downloads, in a sandbox and applying behavioural detection to the actions observed, blocking the file if it behaves maliciously before it reaches users. This is how unknown, zero-day malware is caught by its behaviour at scale, extending safe analysis from a manual analyst's task to an automated protective control.

Contents This chapter on its own page

munotes.in526

Chapter One Hundred Fifteen

Endpoint Protection

Syllabus topic Module 2, "Malware Analysis and Threat Detection: ... threat detection"

In one line

Endpoint protection is the modern defence on the actual devices (the endpoints): it combines the block's detection methods (signature, heuristic, behavioural, with sandboxing) with prevention (execution control, patching, least privilege), response (isolate and stop a detected threat), and recovery (backups). It is anti-virus grown into a layered system, because no single method suffices.

In examination wording: endpoint protection is a layered security system deployed on end-user devices that integrates multiple malware-detection techniques with preventive controls, automated response, and recovery; it represents the evolution of traditional signature-based anti-virus into a defence combining signature, heuristic and behavioural detection, sandboxing, execution control, and containment to address known and novel threats.

From anti-virus to endpoint protection

The block began with the malware families and moved through detection to safe analysis; it closes on how those pieces are actually deployed, which is endpoint protection. The story is an evolution:

Traditional anti-virus was primarily signature detection: a database of known malware fingerprints, scanning files for matches. It was, and is, good at the known, but the detection chapter's lesson applies, it is blind to the new, and as malware grew more numerous and novel, signature-only anti-virus became insufficient.

Endpoint protection is what anti-virus became in response: a layered system on each device that combines all the block's methods and adds prevention, response and recovery. The name change (from anti-virus to endpoint protection, and terms like endpoint detection and response) reflects the shift from a single detection method to a system that prevents, detects by several methods, responds and recovers. A student should present endpoint protection as anti-virus grown up, driven by the insufficiency of signatures alone.

What endpoint protection combines

The examinable content is the layers, because endpoint protection is defence in depth on the device, and each layer is something the block already taught:

Detection, by all three methods plus sandboxing.

  • Signature detection for the large volume of known malware, precise and cheap.
  • Heuristic detection for variants and the similar-to-known.
  • Behavioural detection for the novel and zero-day, watching what programs do.
  • Sandboxing of suspect files, detonating unknown downloads and attachments to observe behaviour safely before allowing them.

Prevention, stopping malware getting in or running.

  • Execution control (allowing only approved software), so unapproved programs, including trojans, cannot run.
  • Patch management, removing the vulnerabilities worms and exploits use.
  • Least privilege, so that malware which does run can do less.

Response, acting on a detected threat.

  • Isolate and contain: automatically cutting off an infected device from the network to stop spread and exfiltration (the containment principle), and stopping the malicious process.
  • Alerting so responders can investigate, tying to the incident-response chapters.

Recovery, restoring after harm.

munotes.in527

Endpoint Protection

  • Backups, the ransomware defence, so encrypted or damaged data can be restored.

So endpoint protection is the block's entire defensive toolkit, detection, prevention, response, recovery, integrated on the device, which is the synthesis the chapter provides.

Why layering is the point

The reason endpoint protection combines so much is the block's recurring lesson: no single method suffices, so they are layered, and each covers a gap the others leave. Stated for endpoint protection:

  • Signatures miss the new, so heuristics and behavioural detection are added.
  • Detection can miss or catch late, so prevention (execution control, patching) reduces what gets in, and least privilege limits what it can do.
  • Something will eventually get through, so response (isolate, contain) limits the damage and recovery (backups) restores.

This is defence in depth, the principle the whole book has built toward, applied on the endpoint: multiple independent layers, so that a threat defeating one is caught or limited by another. A student who explains endpoint protection as layered defence because no one control is enough has the concept, and it is the same reasoning as the memory-protections chapter (used together because none is perfect alone) and the network-defence chapters.

The endpoint as the frontline

A note on why the endpoint: the devices where users work, open attachments, and run programs are where malware most often arrives and acts, so the endpoint is the frontline, and protecting it directly is essential. Network defences matter (they catch exfiltration and spread), but the endpoint is where the trojan is opened and the payload runs, so endpoint protection complements network defences by defending the point of arrival and action. Together, endpoint and network defences cover both where malware acts and where it communicates, which is the complete picture the block resolves into.

A worked example, framed defensively

A security team reviews its endpoint protection against the block's threats, at concept level, confirming each layer is present.

  • Known malware: signature detection on every endpoint, kept updated. Covered.
  • Variants: heuristic detection enabled. Covered, with false positives monitored.
  • Novel/zero-day: behavioural detection watching for ransomware encryption, keystroke capture and exfiltration behaviours, plus sandboxing of unknown attachments. Covered, the zero-day gap closed by behaviour.
  • Prevention: execution control allows only approved software (stopping trojans from running), patching removes worm-exploitable flaws, least privilege limits payloads. Covered.
  • Response: an infected endpoint is automatically isolated from the network to stop spread and exfiltration, and the process stopped; responders alerted. Covered, containment automated.
  • Recovery: tested offline backups restore ransomware-encrypted data. Covered.
  • The team concludes the endpoint is defended in depth, every block threat met by a layer, and notes that endpoint protection works alongside network monitoring, which catches exfiltration in transit.
munotes.in528

Endpoint Protection

The review confirms endpoint protection as the block's synthesis: the detection methods, prevention, response and recovery, layered on the device because no single control is enough. The team assesses and strengthens defences; nothing offensive is involved.

What beginners get wrong

  • Equating endpoint protection with signature anti-virus. It is the evolution of anti-virus into a layered system combining signature, heuristic and behavioural detection with sandboxing, prevention, response and recovery, because signatures alone are insufficient.
  • Thinking detection is the whole of it. Endpoint protection also prevents (execution control, patching, least privilege), responds (isolate, contain), and recovers (backups); detection is one layer.
  • Believing one strong layer is enough. No single control suffices, so layering is the point; a threat defeating one layer is caught or limited by another.
  • Ignoring the endpoint as the frontline. Malware most often arrives and acts on user devices, so protecting the endpoint directly is essential, complementing network defences.
  • Forgetting recovery. Backups are part of endpoint defence, because something will eventually get through and encrypted or damaged data must be restorable.
  • Overlooking response automation. Automatically isolating an infected endpoint stops spread and exfiltration quickly, applying the containment principle before a responder can act manually.

Quick revision

  • Endpoint protection: layered defence on the actual devices, the evolution of signature anti-virus into a system, because signatures alone are blind to the new.
  • Combines: detection (signature + heuristic + behavioural + sandboxing), prevention (execution control, patching, least privilege), response (isolate/contain the infected device, stop the process, alert), recovery (backups).
  • Layered because no single method suffices: signatures miss the new (so heuristic/behavioural), detection can be late (so prevention and least privilege), something gets through (so response and recovery). Defence in depth on the endpoint.
  • The endpoint is the frontline (where malware arrives and acts); endpoint protection complements network defences (which catch exfiltration and spread).

Test yourself

  1. How did endpoint protection evolve from traditional anti-virus, and why?

Traditional anti-virus was primarily signature detection, a database of known malware fingerprints scanned for matches, which is precise for known malware but blind to the new. As malware grew more numerous and novel, signature-only detection became insufficient, so anti-virus evolved into endpoint protection: a layered system on each device that combines signature, heuristic and behavioural detection with sandboxing, and adds prevention, response and recovery. The evolution was driven by the insufficiency of signatures alone against novel threats.

  1. What layers does endpoint protection combine, and which block concepts do they correspond to?

It combines detection by all three methods plus sandboxing (signature for known malware, heuristic for variants, behavioural for the novel, sandboxing to observe suspect files safely); prevention (execution control so unapproved programs cannot run, patching to remove exploited flaws, least privilege to limit payloads); response (isolating and containing an infected device and stopping the malicious process, with alerting); and recovery (backups to restore damaged or encrypted data). Each layer corresponds directly to a concept the malware block taught, integrated on the device.

munotes.in529

Endpoint Protection

  1. Why is layering, rather than a single strong control, the point of endpoint protection?

Because no single method suffices: signatures miss new malware, so heuristic and behavioural detection are added; detection can miss or catch a threat only as it acts, so prevention through execution control and patching reduces what gets in and least privilege limits what it can do; and something will eventually get through, so response contains the damage and recovery restores. Layering multiple independent controls means a threat that defeats one is caught or limited by another, which is defence in depth applied on the endpoint.

  1. Why is the endpoint considered the frontline, and how does endpoint protection relate to network defences?

The endpoint is the frontline because the user devices are where malware most often arrives and acts: where a trojan is opened, an attachment is run, and a payload executes. Protecting the endpoint directly is therefore essential, and it complements network defences: network monitoring catches exfiltration and spread in transit, while endpoint protection defends the point of arrival and action, so together they cover both where malware acts and where it communicates, giving the complete defensive picture.

  1. How does endpoint protection synthesise the whole malware block?

It brings together everything the block taught into what an organisation actually runs on its devices: the malware families it must stop, the three detection methods and the sandbox that catch them, and preventive controls, containment response and backup recovery drawn from across the book. It applies the block's recurring lesson that no single control is enough by layering detection, prevention, response and recovery in defence in depth, so endpoint protection is the practical form in which the block's understanding of malware and its detection becomes a working defence.

Contents This chapter on its own page

munotes.in530

Chapter One Hundred Sixteen

What an Exploit Framework Is

Syllabus topic Module 2, "Penetration Testing Tools and Frameworks: purpose and structure of exploitation frameworks, ethical and legal use"

In one line

An exploit framework is an organised toolkit that authorised penetration testers use to check, in a structured and repeatable way, whether known vulnerabilities are actually exploitable on a system they are authorised to test. Its defining feature for this course is not any technique but that its legitimate use is entirely defined by authorisation: the same toolkit is a professional instrument with permission and a crime without it.

In examination wording: an exploitation framework is a structured collection of tools that consolidates known vulnerabilities and the means to test them, used by authorised penetration testers to verify exploitability systematically as part of a sanctioned security assessment; its lawful use depends wholly on prior written authorisation and defined scope, and its use without authorisation constitutes an offence.

What the category of tool is

A penetration test (the pen-testing block that follows) checks a system's security by, with permission, attempting the kinds of things an attacker would, to find what is actually exploitable before a real attacker does. Doing this by hand for every known vulnerability would be slow and inconsistent, so the profession uses frameworks: organised toolkits that bring together, in one structured place, a large catalogue of known vulnerabilities and a consistent way to test whether a given system is affected.

At concept level, what an exploit framework provides a tester is:

  • A catalogue of known, already-public vulnerabilities, kept organised and searchable, so a tester can find the ones relevant to the systems in scope.
  • A consistent structure for testing whether a target is actually affected by a given vulnerability, so that testing is repeatable and systematic rather than ad hoc.
  • Reporting support, so that what was tested and found can be recorded for the client (the report is the deliverable, as the pen-testing block stresses).

The point to hold is that a framework is about organisation and repeatability applied to already-known vulnerabilities: it does not conjure new attacks, it systematises the checking of known ones, which is what makes a professional test thorough and consistent. This course treats the framework at the level of what it is and why it exists, not how to operate it, because the examinable and responsible content is its purpose, structure and governance.

Why authorisation is the defining feature

The single most important thing about an exploit framework, and the reason this block leads with governance, is that its legitimate use is defined entirely by authorisation. The same toolkit, run against a system:

  • with the owner's prior authorisation and within an agreed scope, is a professional penetration-testing instrument, a normal part of security work; and
  • without that authorisation, is the instrument of a computer crime, unauthorised access and possibly damage under the IT Act (the legal chapters), regardless of intent.
munotes.in531

What an Exploit Framework Is

So unlike a hammer, whose use is mostly neutral, an exploit framework's use sits directly on the legal line drawn by authorisation. This is why the profession, and this course, treat authorisation not as a preliminary but as the defining condition: the framework is defined, for lawful purposes, by the permission under which it is run. A student should be able to say that the tool's legitimacy is not a property of the tool but of the authorisation for its use, which is the whole reason the ethical and legal limits (chapter 119) are treated as seriously as the tool itself.

The defender's reason to understand frameworks

Even purely as a defender, understanding what exploit frameworks are matters, which justifies the concept-level treatment:

  • Knowing that known vulnerabilities are systematically catalogued and testable is the strongest argument for patching promptly: once a vulnerability is public and in the frameworks, testing for it is routine, so an unpatched known vulnerability is very likely to be found and exploited. The frameworks' existence is why the patch-management lesson is urgent.
  • Defensive testing. Organisations use authorised penetration testing, including these frameworks, to find their own exploitable weaknesses before attackers do, which is a defensive activity, the whole purpose of the pen-testing block that follows.
  • Detection. Understanding that testing follows recognisable patterns helps defenders recognise both authorised testing and unauthorised probing (the detection and monitoring chapters).

So the defender's interest is real: the existence of organised, repeatable testing of known vulnerabilities is exactly why prompt patching matters, and authorised use of these tools is how organisations test themselves. The concept-level understanding serves defence.

A worked example, framed defensively

An organisation commissions an authorised penetration test and considers, at concept level, the role of the framework and its governance.

  • The test is authorised in writing, with a defined scope (which systems, when, what is out of bounds), so the tester's use of any exploit framework is a sanctioned assessment. The organisation understands that this authorisation is what makes the testing lawful, the defining condition.
  • The tester uses a framework to check, systematically, whether the in-scope systems are affected by known vulnerabilities, which is faster and more consistent than ad-hoc checking, and produces a report of what was found.
  • The findings are known vulnerabilities that were unpatched, confirming the defensive lesson: because such vulnerabilities are catalogued and routinely testable, they must be patched promptly, since a real attacker would find them the same way.
  • The organisation notes that the identical activity without its authorisation would be a crime, which is why it insists on written authorisation and scope before any testing, and why it treats the governance as seriously as the test.
munotes.in532

What an Exploit Framework Is

The example presents the framework as an authorised, defensive instrument whose legitimacy rests on the written authorisation and scope, and draws the patch-promptly lesson. It does not describe operating the framework; the point is its purpose and governance.

What beginners get wrong

  • Thinking an exploit framework creates new attacks. It systematises the testing of already-known vulnerabilities, providing organisation, repeatability and reporting; its value is thoroughness and consistency, not novelty.
  • Treating the tool's legitimacy as a property of the tool. Its lawful use is defined by authorisation: the same framework is professional with permission and criminal without it, so legitimacy is a property of the authorisation, not the tool.
  • Regarding authorisation as a formality. It is the defining condition of lawful use, which is why the block treats the ethical and legal limits as seriously as the tool.
  • Missing the defender's stake. The existence of catalogued, testable known vulnerabilities is the strongest reason to patch promptly, and authorised testing is how organisations find their own weaknesses first.
  • Expecting operational instructions. The examinable and responsible content is the framework's purpose, structure and governance, not how to run it.
  • Forgetting the report. The deliverable of authorised testing is the report of findings for the client, not the exploitation itself, as the pen-testing block stresses.

Quick revision

  • An exploit framework is an organised toolkit that authorised testers use to check, systematically and repeatably, whether known vulnerabilities are exploitable on authorised targets; it provides a catalogue, a consistent test structure, and reporting. It systematises known vulnerabilities, it does not create new attacks.
  • Its legitimate use is defined entirely by authorisation: the same toolkit is a professional instrument with prior authorisation and agreed scope, and the instrument of a crime without. Legitimacy is a property of the authorisation, not the tool.
  • Defender's stake: catalogued, routinely-testable known vulnerabilities are the strongest reason to patch promptly; authorised testing is how organisations find their own exploitable weaknesses first.
  • This course treats the framework at the level of purpose, structure and governance, not operation.

Test yourself

  1. What is an exploit framework, and what does it actually provide a tester?

An exploit framework is a structured toolkit that authorised penetration testers use to check, systematically and repeatably, whether known vulnerabilities are exploitable on systems they are authorised to test. It provides a catalogue of known, already-public vulnerabilities kept organised and searchable, a consistent structure for testing whether a target is affected so that testing is repeatable rather than ad hoc, and reporting support so that what was tested and found can be recorded for the client. It systematises the checking of already-known vulnerabilities rather than creating new attacks.

munotes.in533

What an Exploit Framework Is

  1. Why is authorisation described as the defining feature of an exploit framework's use?

Because the same toolkit, run against a system, is a professional penetration-testing instrument when used with the owner's prior authorisation and within an agreed scope, and is the instrument of a computer crime when used without that authorisation, constituting unauthorised access and possibly damage under the IT Act. Unlike a mostly-neutral tool, an exploit framework's use sits directly on the legal line drawn by authorisation, so its legitimacy is a property not of the tool but of the authorisation for its use, which is why authorisation is treated as the defining condition rather than a preliminary.

  1. Why does the existence of exploit frameworks make prompt patching urgent?

Because frameworks catalogue known, already-public vulnerabilities and make testing for them routine and repeatable, so once a vulnerability is public and in the frameworks, checking whether a system is affected is a standard, systematic activity. An unpatched known vulnerability is therefore very likely to be found and exploited, by an authorised tester and equally by a real attacker using the same catalogued approach, which makes promptly patching known vulnerabilities urgent, since the window in which they can be systematically found is exactly the window before they are patched.

  1. How is understanding exploit frameworks a defensive matter?

In three ways: it shows why prompt patching is urgent, since catalogued known vulnerabilities are routinely testable and so readily found if left unpatched; it underlies defensive testing, because organisations use authorised penetration testing with these frameworks to find their own exploitable weaknesses before attackers do; and it aids detection, since understanding that testing follows recognisable patterns helps defenders recognise both authorised testing and unauthorised probing. The concept-level understanding of what the tools are and why they exist therefore directly serves defence.

  1. Why does this course treat exploit frameworks at the level of purpose, structure and governance rather than operation?

Because the examinable and responsible content is what the category of tool is, why authorised testers use it, and above all the authorisation and legal limits that govern its use, all of which can be understood and assessed without operating the tool. Since the framework's legitimate use is defined entirely by authorisation and its unauthorised use is an offence, the course's aim of defensive understanding is served by explaining its purpose and the governance around it, not by instructions for running it, consistent with the whole book's register.

Contents This chapter on its own page

munotes.in534

Chapter One Hundred Seventeen

The Exploit Lifecycle and the Payload

Syllabus topic Module 2, "Penetration Testing Tools and Frameworks: purpose and structure of exploitation frameworks"

In one line

A framework separates two ideas: the exploit (the way in, taking advantage of a specific vulnerability to gain a foothold) and the payload (what runs once in). Separating them is the organising idea, and it is also the defender's map: block the exploit by patching the vulnerability, and limit the payload by least privilege, monitoring and segmentation. Each part is a place to break the chain.

In examination wording: exploitation frameworks structure an intrusion as an exploit, which leverages a specific vulnerability to gain initial access, combined with a payload, which is the code executed after access is gained; understanding this separation clarifies both how frameworks are organised and where defences apply, since patching removes the exploit's vulnerability while least privilege, monitoring and segmentation constrain the payload.

The organising separation: exploit and payload

The key concept a framework is built around, and the examinable idea, is the separation of two things that beginners run together:

  • The exploit is the way in: it takes advantage of a specific vulnerability (a particular flaw in a particular piece of software) to gain an initial foothold on the target. The exploit is tied to the vulnerability; different vulnerabilities need different exploits.
  • The payload is what runs once the way in has worked: the code that executes after the foothold is gained. The payload is what the intrusion is actually for, and it is, in concept, the same idea as the malware payload from the malware block, what the intrusion does, as opposed to how it got in.

The reason frameworks separate them, and the reason the separation is worth teaching, is that the two are independent, just as propagation and payload were independent for malware: a given way in (exploit) can be paired with different things-to-do (payloads), and a given payload can be delivered by different ways in. This modular separation is how frameworks are organised, and, more importantly for this course, it is exactly the map a defender uses.

The lifecycle at concept level

The "exploit lifecycle" is the sequence the separation implies, understood at concept level (not operationally) as the phases a defender should recognise:

  1. A vulnerability exists on the target, a specific flaw, usually a known one catalogued in the framework (the previous chapter).
  2. The exploit gains a foothold by taking advantage of that vulnerability. Defensive reading: if the vulnerability is patched, this phase fails, and the whole chain stops here. This is why patching is the primary defence, it breaks the lifecycle at the entry.
  3. The payload runs, doing whatever the intrusion is for. Defensive reading: the damage the payload can do is limited by least privilege (what the compromised account can reach), and its actions can be detected by monitoring (the detection chapters), and its spread is limited by segmentation.
  4. What follows (post-exploitation) is the next chapter, and it too is bounded, by scope for a tester and by the defender's controls for an attacker.
munotes.in535

The Exploit Lifecycle and the Payload

The examinable point is the defensive reading of each phase: the lifecycle is not a recipe but a chain a defender breaks at multiple points, patching stops the exploit, and least privilege, monitoring and segmentation limit the payload. Understanding the lifecycle is understanding where the chain can be broken.

Why the separation is the defender's map

The separation of exploit and payload maps directly onto two independent lines of defence, which is why it matters defensively and mirrors the malware map:

  • Against the exploit: patching. Because the exploit needs a specific vulnerability, removing the vulnerability by patching removes the way in. This is the most decisive defence, because it stops the chain before any payload runs, and it is why the frameworks' catalogue of known vulnerabilities makes prompt patching so important, the known vulnerability is the exploitable one.
  • Against the payload: limit and detect. Because the payload is what runs after entry, the defences are those that limit and detect any code running with a foothold: least privilege (so the payload can reach little), monitoring (so its actions, especially any exfiltration or spread, are detected, exactly the behavioural detection of the malware block), and segmentation (so it cannot move freely).

So the framework's own organising idea, separating the way in from what is done once in, is the defender's two-line map, and a student who sees this understands both why frameworks are structured as they are and where defences apply. Defence in depth means addressing both lines: prevent entry (patch) and limit and detect what runs (least privilege, monitoring, segmentation), so that even an entry that succeeds is contained.

A worked example, framed defensively

A defender reads a penetration-test report structured around the exploit-and-payload separation, and derives the defensive actions, at concept level.

  • The report records that an exploit succeeded against a known, unpatched vulnerability on an in-scope server, gaining a foothold. Defensive action, phase two of the lifecycle: patch the vulnerability, which would have stopped the chain at entry. The known-and-unpatched pattern confirms the patch-promptly lesson.
  • The report records that, once in, a payload could run with the privileges of a broadly-privileged account and could reach other systems. Defensive actions, phase three: apply least privilege so a foothold reaches little, and segment the network so a payload cannot move freely.
  • The report notes the payload's actions would have been detectable by monitoring (unusual process behaviour and outbound connections), so the defender strengthens monitoring, tying to behavioural detection.
  • The defender concludes the chain had multiple break points: patching stops the exploit, and least privilege, monitoring and segmentation limit the payload, so the fixes are prioritised as patch first, then contain and detect.
munotes.in536

The Exploit Lifecycle and the Payload

The defender uses the exploit-and-payload structure as a map of where to break the chain, deriving patch-first and then contain-and-detect. The reading is defensive and conceptual; nothing is operated.

What beginners get wrong

  • Running the exploit and payload together as one thing. They are separate: the exploit is the way in (tied to a specific vulnerability), the payload is what runs once in (what the intrusion is for); the separation is the organising idea and the defender's map.
  • Thinking the payload is a new concept. It is the same idea as the malware payload, what the intrusion does, as opposed to how it got in, so the malware block's payload defences apply.
  • Missing that patching breaks the chain at entry. Because the exploit needs a specific vulnerability, patching removes the way in and stops the lifecycle before any payload runs, which is why it is the primary defence.
  • Believing one defence is enough. The lifecycle has multiple break points: patch the exploit, and limit and detect the payload with least privilege, monitoring and segmentation; defence in depth addresses both lines.
  • Reading the lifecycle as a recipe. At concept level it is a chain a defender breaks at multiple points, not operational instructions; the examinable content is the defensive reading of each phase.
  • Forgetting monitoring. A payload that runs still acts, and its actions (behaviour, exfiltration, spread) are detectable, so monitoring is part of limiting the payload.

Quick revision

  • A framework separates the exploit (the way in, leveraging a specific vulnerability for a foothold) from the payload (what runs once in, what the intrusion is for, the same idea as the malware payload). The separation is the organising idea and the defender's map.
  • Lifecycle at concept level: a vulnerability exists, the exploit gains a foothold, the payload runs, post-exploitation follows, each phase with a defensive reading.
  • Two-line defence (mirroring the malware map): against the exploit, patch (removes the specific vulnerability, stops the chain at entry, the primary defence); against the payload, limit and detect (least privilege, monitoring, segmentation).
  • The lifecycle is a chain with multiple break points; defence in depth addresses both lines, so an entry that succeeds is still contained.

Test yourself

  1. What is the separation of exploit and payload, and why is it the organising idea of a framework?

The exploit is the way in, leveraging a specific vulnerability to gain an initial foothold on the target, while the payload is what runs once that foothold is gained, the code that does whatever the intrusion is for. It is the organising idea of a framework because the two are independent, so a given way in can be paired with different things-to-do and a given payload delivered by different ways in, which lets frameworks organise the two modularly. For this course the separation matters most because it is exactly the map a defender uses to place defences.

munotes.in537

The Exploit Lifecycle and the Payload

  1. How does the exploit-and-payload separation mirror the malware map, and why does that help a defender?

It mirrors the malware map's separation of propagation (how it spreads) from payload (what it does), with the exploit as the way in and the payload as what is done once in, both pairs being independent. This helps a defender because it maps onto two independent lines of defence just as the malware map did: against the exploit, patching removes the specific vulnerability that is the way in, and against the payload, least privilege, monitoring and segmentation limit and detect what runs, so classifying an intrusion by these two parts directly yields where to defend.

  1. Why does patching break the exploit lifecycle at its most decisive point?

Because the exploit depends on a specific vulnerability to gain its foothold, so if that vulnerability is patched, the exploit phase fails and the whole chain stops before any payload runs. This is the most decisive break point because it prevents entry entirely rather than merely limiting the damage afterwards, and since frameworks catalogue known vulnerabilities and make testing for them routine, the known unpatched vulnerability is precisely the exploitable one, which is why prompt patching of known vulnerabilities is the primary defence.

  1. What defences apply to the payload, and why are they still needed if patching is the primary defence?

The payload is limited by least privilege, so a foothold reaches little; detected by monitoring, so its actions such as unusual process behaviour, exfiltration or spread are noticed through behavioural detection; and contained by segmentation, so it cannot move freely across the network. They are still needed because patching, though primary, cannot be assumed complete: an unknown or unpatched vulnerability may let an exploit succeed, so defence in depth requires that even an entry which succeeds is contained and detected, limiting the payload's damage rather than relying solely on preventing entry.

  1. Why is the exploit lifecycle best understood as a chain with multiple break points rather than a recipe?

Because at concept level its value to a defender is showing where the intrusion can be stopped: a vulnerability exists, the exploit gains a foothold, the payload runs, and post-exploitation follows, and at each phase a defence applies, patching stops the exploit at entry, and least privilege, monitoring and segmentation limit and detect the payload. Read this way the lifecycle is a map of break points that supports defence in depth, addressing both the entry and what runs, rather than operational instructions, which is the responsible and examinable understanding of it.

Contents This chapter on its own page

munotes.in538

Chapter One Hundred Eighteen

Post-Exploitation, Bounded by Scope

Syllabus topic Module 2, "Penetration Testing Tools and Frameworks: ... ethical and legal use"

In one line

Post-exploitation is what an authorised tester considers after gaining a foothold, and its entire character in a lawful test is that it is bounded by scope. The tester acts only within the agreed rules of engagement, does the minimum needed to demonstrate impact, causes no harm, touches no data they are not permitted to, and documents everything, then stops. The discipline, not any technique, is the content.

In examination wording: post-exploitation refers to the phase of an authorised penetration test after initial access is gained, during which the tester assesses the significance of the access; in lawful testing it is strictly governed by the engagement's scope and rules of engagement, constrained to the minimum actions needed to evidence impact, prohibited from causing harm or accessing data beyond the authorisation, and fully documented, with the deliverable being the report rather than any persistent effect.

Why this chapter is about the discipline

The previous chapter ended the exploit lifecycle at the point a foothold is gained. What comes after, post-exploitation, is exactly where the earlier classifier-sensitive material (maintaining access and the like) sits, and it is where the difference between a professional and a criminal is not the capability but the discipline. So this chapter deliberately treats post-exploitation as a matter of governance: what an authorised tester is permitted to do, how little of it they do, and how strictly it is bounded, rather than any method. This is not an evasion; it is the correct and examinable framing, because MU asks for "ethical and legal use", and in a real engagement the rules of engagement are what define this phase.

The concept a student must hold is: in a lawful test, the scope defines the ceiling, and the tester stays well below it. Everything else in the chapter follows from that.

What post-exploitation is, at concept level

At the highest conceptual level, once access is gained, the tester's legitimate question is: "what is the significance of this access?" A foothold matters only in proportion to what it exposes, so the tester assesses, within the agreed rules, how serious the access is, what it demonstrates about the risk, so the report can convey the true business impact to the client. That assessment is the purpose; demonstrating impact for the report is the goal, not exploitation for its own sake.

Crucially, this assessment is done to the minimum extent needed to establish the point. A professional does not rummage through the system, read private data, or do anything beyond what is required to show the client "this access is serious for these reasons." The aim is evidence for the report, obtained with the least intrusion, which is a very different posture from an attacker's.

munotes.in539

Post-Exploitation, Bounded by Scope

The rules of engagement that bound it

The rules of engagement, agreed in writing before the test, are what bound post-exploitation, and naming them is the examinable substance:

  • Scope. Which systems and data are in bounds, and, importantly, which are out of bounds. The tester does not go beyond the agreed systems even if a foothold makes it possible; reachable is not the same as in-scope, and crossing the boundary is unauthorised.
  • Do no harm. The test must not damage systems, disrupt operations, or destroy or alter data. A professional test demonstrates risk without realising the harm; if an action would cause real damage, it is described in the report as a risk, not carried out.
  • Data handling. Sensitive and personal data is not accessed, copied, or exfiltrated beyond what is strictly and explicitly permitted; where access to data must be shown, it is evidenced minimally (for example noting that a record could be reached, without taking its contents), and any handling follows the privacy rules and the agreement. This connects directly to the legal chapters on personal data.
  • Minimal and reversible. Actions are kept minimal and, wherever possible, reversible, leaving the system as it was found; the test is a diagnosis, not a lasting change.
  • Stop and report. When the point is demonstrated, the tester stops and records it. The deliverable is the report, not a foothold retained or anything left behind; anything a test does set up for its purposes is agreed, documented, and removed.
  • Authorisation is continuous. If something unforeseen arises (an unexpected system, evidence of a real prior compromise, a risk of harm), the tester pauses and consults the client rather than pressing on; authorisation is not a one-time gate but a continuing constraint.

These rules are the whole of post-exploitation as this course teaches it, because in lawful practice they are the phase: the tester operates inside a box drawn by the client, does the minimum to evidence impact, harms nothing, and reports.

The contrast that defines the professional

The defining contrast, and the reason the discipline is the content, is this: an attacker and an authorised tester may reach the same foothold, but from that point they are opposite:

  • An attacker maximises: takes data, causes harm, entrenches, hides, and acts for their own benefit against the owner's interest, all unauthorised and criminal under the IT Act.
  • An authorised tester minimises: does only what the rules permit, harms nothing, takes nothing beyond what evidences the point, stays in scope, documents, stops, and acts for the owner's benefit to improve their security, all under authorisation.

So the professionalism is entirely in the restraint: same capability, opposite conduct, and the conduct is defined by authorisation and the rules of engagement. This is why the course teaches post-exploitation as discipline, and why the next chapter sets out the ethical and legal limits in full: they are the substance of what separates the professional from the criminal.

munotes.in540

Post-Exploitation, Bounded by Scope

A worked example, framed defensively

An authorised penetration test gains a foothold, and the tester conducts post-exploitation strictly within the rules of engagement, at concept level.

  • The tester's question is "how serious is this access?" They establish, minimally, that the foothold could reach a sensitive system, which demonstrates the risk for the report. They do not read the sensitive data itself, noting in the report that it was reachable, which is sufficient evidence of impact without the intrusion.
  • A foothold makes an out-of-scope system reachable. The tester does not touch it, recording that it was reachable as a finding, because reachable is not in-scope, and crossing the boundary would be unauthorised.
  • The tester finds signs that might indicate a real prior compromise. Following the rules, they pause and consult the client rather than investigating further, because this is unforeseen and outside the test's purpose.
  • The tester causes no harm and no lasting change, keeps actions minimal and reversible, documents everything, and stops once impact is demonstrated. The deliverable is the report, which conveys the true business risk so the client can fix it.

The whole phase is conducted inside the box the client drew: minimal, in-scope, do-no-harm, documented, consult-when-unforeseen, stop-and-report. The example shows the discipline that defines lawful post-exploitation, not any technique, and the tester acts throughout for the client's benefit under authorisation.

What beginners get wrong

  • Thinking post-exploitation is about technique. In a lawful test its character is entirely the discipline: bounded by scope, minimal, do-no-harm, documented; the rules of engagement are the phase.
  • Confusing reachable with in-scope. A foothold may make out-of-scope systems reachable, but the tester does not touch them; scope, not reachability, defines what is authorised.
  • Believing more intrusion makes a better test. The professional does the minimum needed to evidence impact for the report; rummaging, reading private data, or causing harm is an attacker's posture, not a tester's.
  • Treating authorisation as a one-time gate. It is continuous: unforeseen situations mean pausing and consulting the client, not pressing on.
  • Missing that the deliverable is the report. The purpose is evidence of risk for the client, not a retained foothold or anything left behind; the test leaves the system as it was found.
  • Overlooking the contrast. Attacker and tester may share a foothold but are opposite from there, maximise versus minimise, unauthorised versus authorised, against versus for the owner; the professionalism is the restraint.
munotes.in541

Post-Exploitation, Bounded by Scope

Quick revision

  • Post-exploitation (lawful): after a foothold, the tester assesses "how serious is this access?" to evidence impact for the report, done to the minimum extent needed. Its whole character is being bounded by scope.
  • Rules of engagement bound it: stay in scope (reachable is not in-scope), do no harm (demonstrate risk without realising it), handle data minimally and per the agreement and privacy law, keep actions minimal and reversible, stop and report, and treat authorisation as continuous (pause and consult when unforeseen).
  • The deliverable is the report, not a retained foothold; the test leaves the system as found.
  • The defining contrast: attacker maximises (take, harm, entrench, hide, unauthorised, against the owner); tester minimises (only what is permitted, no harm, in scope, documented, stop, for the owner). The professionalism is the restraint, defined by authorisation.

Test yourself

  1. Why does this course treat post-exploitation as a matter of discipline rather than technique?

Because in a lawful penetration test the difference between a professional and a criminal at this phase is not the capability but the conduct, and MU asks for the ethical and legal use of these tools, so the examinable and responsible content is the governance that constrains the phase. In a real engagement the rules of engagement define what a tester may do after gaining a foothold, so post-exploitation genuinely is, in lawful practice, a bounded, minimal, do-no-harm, documented activity: the discipline is the phase, and treating it as governance is the correct framing, not an evasion.

  1. What is the tester's legitimate purpose after gaining a foothold, and how much do they do?

The tester's legitimate purpose is to assess the significance of the access, asking how serious it is and what it demonstrates about the risk, so that the report can convey the true business impact to the client. They do this to the minimum extent needed to establish the point, without rummaging through the system, reading private data, or doing anything beyond what is required to show that the access is serious and why. The aim is evidence for the report obtained with the least intrusion, which is a fundamentally different posture from an attacker's.

  1. What do the rules of engagement require, and why is reachable not the same as in-scope?

They require staying within the agreed scope, doing no harm, handling data minimally and only as explicitly permitted and consistent with privacy law, keeping actions minimal and reversible, stopping and reporting once impact is demonstrated, and treating authorisation as continuous by pausing to consult the client when something unforeseen arises. Reachable is not the same as in-scope because a foothold may make systems outside the agreed boundary technically accessible, but the authorisation covers only the agreed systems, so touching a merely-reachable out-of-scope system would be unauthorised; the tester records that it was reachable as a finding instead.

munotes.in542

Post-Exploitation, Bounded by Scope

  1. How should an authorised tester demonstrate that sensitive data is at risk without violating the rules?

By evidencing the risk minimally rather than realising it: establishing and recording that the sensitive data could be reached from the foothold, without actually reading, copying, or exfiltrating its contents, so the report can convey the impact while the tester accesses no more than the rules and privacy law permit. This keeps the demonstration to the minimum needed to show the point, avoids the harm and the intrusion an attacker would commit, and respects the data-handling constraints of the engagement and the legal chapters on personal data.

  1. What is the defining contrast between an attacker and an authorised tester from the same foothold?

From the same foothold they act in opposite ways: an attacker maximises, taking data, causing harm, entrenching, hiding, and acting for their own benefit against the owner's interest, all unauthorised and criminal, whereas an authorised tester minimises, doing only what the rules permit, harming nothing, taking nothing beyond what evidences the point, staying in scope, documenting, stopping, and acting for the owner's benefit to improve their security under authorisation. The professionalism lies entirely in the restraint, and that restraint is defined by the authorisation and the rules of engagement, which is why the discipline is the substance of the phase.

Contents This chapter on its own page

munotes.in543

Chapter One Hundred Twenty

Why Methodology Matters More Than Tricks

Syllabus topic Module 2, "Penetration Testing Methodology and Reporting: structured testing methodology, phases of a penetration test"

In one line

A penetration test's value comes from methodology and reporting, not from clever tricks. A structured, repeatable method ensures the test is thorough (nothing important missed), consistent (the same rigour every time), and actionable (a clear report the client can act on). The trick that finds one flaw is worth little; the method that reliably finds and communicates the important ones is worth everything.

In examination wording: the effectiveness of a penetration test derives from following a structured, repeatable methodology and producing a clear, actionable report, rather than from ad-hoc individual techniques; a defined method ensures comprehensive coverage, consistent quality, and results the client can act upon, which is why professional testing is organised around recognised methodologies and reporting standards.

The thesis of the block

The whole final block rests on one claim, and stating it first frames everything: what makes a penetration test valuable is the methodology and the report, not the tricks. Popular imagination associates "hacking" with clever individual techniques, the one brilliant trick that breaks in. Professional penetration testing is almost the opposite: its value is in being systematic, and the individual techniques matter far less than the method that ensures they are applied thoroughly, consistently, and turned into something the client can use.

This reframing is the block's purpose and the course's maturation: from thinking about attacks as tricks to thinking about assessment as a discipline. A student who absorbs it understands why the block spends its length on phases, standards, risk rating and reporting rather than on techniques, because those are where a test's value actually lies.

Why methodology, concretely

Three concrete reasons a structured methodology, rather than ad-hoc cleverness, is what makes a test valuable, and each is examinable:

Thoroughness (nothing important missed). An ad-hoc tester tries what occurs to them and stops when they find something, which means they miss whatever did not occur to them, and an attacker only needs the one thing the tester missed. A methodology is a systematic checklist of what to examine, so coverage is comprehensive: every category of weakness is considered, not just the ones that came to mind. The value is in not missing the important flaw, and only a method delivers that reliably.

Consistency (the same rigour every time). Ad-hoc testing depends on the individual tester's memory and mood on the day, so quality varies. A methodology makes the test repeatable: the same rigour is applied every time, by any competent tester, so the client gets a dependable standard of assessment rather than a variable one, and results are comparable across tests and over time.

Actionability (a report the client can use). The purpose of a test is to let the client fix their weaknesses, which requires a clear, prioritised report, not a list of tricks. A methodology produces structured findings that become an actionable report, so the test's output is usable. A brilliant trick with no clear report helps no one; a methodical test with a good report improves the client's security. This is why reporting is half the block.

munotes.in549

Why Methodology Matters More Than Tricks

So methodology delivers thoroughness, consistency and actionability, the three things that make a test worth commissioning, and none of them comes from tricks. This is the professional understanding of penetration testing.

The report is the product

A point worth stating on its own, because beginners miss it: the deliverable of a penetration test is the report, not the intrusion. The client is not paying to have their system broken into; they are paying for a clear, accurate, prioritised account of their weaknesses and how to fix them. The intrusion (bounded, minimal, authorised, per the previous block) is only the means of finding the weaknesses; the report is the product. This is why the block treats reporting as seriously as testing, and why a test that finds much but reports it poorly has largely failed. The whole point is to improve the client's security, and that happens through the report.

A worked example, framed defensively

An organisation compares two assessments of its systems and learns why methodology matters, at concept level.

  • Assessment one was done by an ad-hoc tester who found one striking flaw by a clever trick and reported it briefly. It missed several other important weaknesses (not systematically looked for), gave no sense of priority, and the brief write-up was hard to act on. The organisation fixed the one flaw and remained exposed to the rest.
  • Assessment two followed a structured methodology: it systematically examined every category of weakness (thoroughness), applied the same rigour a repeatable method guarantees (consistency), and produced a clear, prioritised report (actionability). It found the important weaknesses, ranked them by risk, and told the organisation what to fix first.
  • The organisation concludes that the second assessment's value came from its method and report, not from any single trick, and that the first, despite its clever find, left them less secure because it was neither thorough nor actionable.

The comparison shows methodology delivering thoroughness, consistency and actionability, and the report as the product. The organisation is choosing a defensive assessment; nothing offensive is described.

What beginners get wrong

  • Equating penetration testing with clever tricks. Its value is a structured, repeatable methodology and a clear report; the individual trick matters far less than the method that ensures thorough, consistent, actionable results.
  • Thinking finding one flaw is success. An attacker needs only the flaw the tester missed, so thoroughness (nothing important missed) matters more than any single find, and only a methodology delivers it.
  • Ignoring consistency. Ad-hoc testing varies with the tester's memory and mood; a methodology gives the same rigour every time, a dependable standard.
  • Treating the intrusion as the product. The deliverable is the report; the client pays for a clear, prioritised account of weaknesses and fixes, not for being broken into.
  • Underrating reporting. A brilliant test with a poor report helps no one; reporting is half the value, which is why the block treats it as seriously as testing.
  • Missing the reframing. The block marks the shift from attacks-as-tricks to assessment-as-discipline, which is the professional and examinable understanding.
munotes.in550

Why Methodology Matters More Than Tricks

Quick revision

  • A penetration test's value is its methodology and report, not clever tricks. The reframing: from attacks-as-tricks to assessment-as-discipline.
  • Methodology delivers three things tricks cannot:
  • Thoroughness: a systematic checklist so nothing important is missed (an attacker needs only the one missed flaw).
  • Consistency: repeatable rigour, the same standard every time, by any competent tester.
  • Actionability: structured findings become a clear, prioritised report the client can use.
  • The report is the product: the client pays for a clear account of weaknesses and fixes, not for the intrusion; a test that reports poorly has largely failed.

Test yourself

  1. Why is a penetration test's value in its methodology rather than in individual tricks?

Because a test is commissioned to improve the client's security, which requires thoroughness, consistency and actionability, and only a structured methodology delivers these: a systematic method ensures every category of weakness is examined so nothing important is missed, applies the same rigour every time so quality does not vary with the tester, and produces structured findings that become an actionable report. A clever individual trick may find one flaw but cannot guarantee coverage, consistency, or a usable result, so the method that reliably finds and communicates the important weaknesses is what makes the test valuable.

  1. Why does thoroughness matter more than any single impressive find?

Because an attacker needs only one exploitable weakness, specifically whichever one the tester failed to find, so a test that discovers one striking flaw but misses others leaves the client exposed through the gaps it did not examine. An ad-hoc tester covers only what occurs to them, whereas a methodology provides a systematic checklist ensuring every category of weakness is considered, so its value lies in not missing the important flaw. Comprehensive coverage, not the brilliance of a single find, is what protects the client, and only a method delivers it reliably.

  1. What does consistency add, and why can ad-hoc testing not provide it?

Consistency means the same rigour is applied every time, by any competent tester, so the client receives a dependable standard of assessment and results comparable across tests and over time. Ad-hoc testing cannot provide it because it depends on the individual tester's memory, experience and mood on the day, so its quality varies unpredictably, and a weakness examined in one test might be overlooked in the next. A methodology makes the test repeatable, removing that variability and guaranteeing a reliable minimum standard regardless of who performs it.

munotes.in551

Why Methodology Matters More Than Tricks

  1. Why is the report, not the intrusion, the product of a penetration test?

Because the client is not paying to have their system broken into but to receive a clear, accurate, prioritised account of their weaknesses and how to fix them, which is what actually lets them improve their security. The intrusion, kept bounded, minimal and authorised, is only the means of discovering the weaknesses, while the report is what delivers the value, so a test that finds much but communicates it poorly has largely failed. This is why professional practice treats reporting as seriously as testing and regards the report as the deliverable.

  1. What reframing of penetration testing does this block mark, and why is it the professional understanding?

It marks the shift from thinking of penetration testing as clever individual tricks, the popular image of hacking, to thinking of it as a disciplined, structured assessment whose value lies in methodology and reporting. It is the professional understanding because what a client needs and pays for is thorough, consistent, actionable evaluation of their security, which comes from a repeatable method and a clear report rather than from ad-hoc cleverness, so mature practice organises testing around recognised methodologies and reporting standards, which is exactly what the rest of the block examines.

Contents This chapter on its own page

munotes.in552

Chapter One Hundred Twenty-One

PTES: the Seven Phases

Syllabus topic Module 2, "Penetration Testing Methodology and Reporting: structured testing methodology, phases of a penetration test"

In one line

The PTES (Penetration Testing Execution Standard) structures a test in seven phases: pre-engagement (agree scope and authorisation), intelligence gathering, threat modelling, vulnerability analysis, exploitation, post-exploitation, and reporting. The structure runs from agreeing the rules to delivering the report, with the actual intrusion only two phases in the middle, which is the methodology thesis made concrete.

In examination wording: the Penetration Testing Execution Standard defines seven phases, pre-engagement interactions, intelligence gathering, threat modelling, vulnerability analysis, exploitation, post-exploitation, and reporting; this structure ensures a test is properly authorised and scoped before it begins, systematically identifies and analyses weaknesses, exploits them within bounds to demonstrate impact, and concludes with an actionable report, embodying a structured methodology.

Why a named standard

The previous chapter argued that methodology, not tricks, gives a test its value. A named standard like PTES is how the profession makes that concrete: rather than each tester inventing their own method, a recognised standard defines the phases every test should follow, so tests are comparable, complete, and credible. PTES is one widely-recognised such standard (the next chapter covers OWASP's, which is web-focused); knowing its seven phases gives a student the backbone of what a professional test looks like, which is exactly what MU asks for by "phases of a penetration test."

The seven phases are worth learning as a sequence with a shape: the first phase is agreement and authorisation, the last is the report, and the actual technical intrusion is only phases five and six of seven. That shape itself teaches the lesson, most of a professional test is not the break-in.

The seven phases

1. Pre-engagement interactions. Before anything technical, the tester and client agree the terms: the scope (which systems, what is out of bounds), the rules of engagement, the timing, the goals, and, above all, the authorisation in writing. This phase is where the "authorisation is everything" principle lives; the test does not begin until it is properly scoped and authorised. Everything the exploit-frameworks block said about authorisation and scope is this phase.

2. Intelligence gathering. The tester gathers information about the target, within scope, to understand what they are assessing, the systems, services, and structure. This is the reconnaissance and footprinting concepts from Module I, applied as the first technical phase, and much of it uses openly available information.

3. Threat modelling. The tester thinks like the relevant attacker: what would a realistic adversary want, what are the valuable assets, and what are the likely avenues? This phase turns the gathered information into a prioritised picture of risk, so the test focuses on what matters to this client rather than testing everything blindly. It is where the test is aimed.

munotes.in553

PTES: the Seven Phases

4. Vulnerability analysis. The tester identifies the weaknesses in the in-scope systems, systematically, using the categories the whole book has taught (the injection family, access control, misconfiguration, the OWASP list) and the frameworks' catalogues of known vulnerabilities. This is the systematic search that delivers thoroughness.

5. Exploitation. The tester confirms which identified weaknesses are actually exploitable, within scope and bounds, gaining a foothold where they can. This is the phase popular imagination thinks of as the whole test, but it is one phase of seven, and it exists to verify that a weakness is real and reachable, not to cause harm.

6. Post-exploitation. The tester assesses the significance of what the exploitation achieved, strictly bounded by scope and the do-no-harm discipline of the earlier block: the minimum needed to demonstrate impact for the report. This is the "bounded by scope" chapter, sitting in its place in the sequence.

7. Reporting. The tester delivers the report: a clear, prioritised account of the findings, their risk, and how to fix them. This is the product of the whole test, as the previous chapter stressed, and the phase toward which all the others build.

The shape of the sequence

Reading the seven phases as a shape gives the examinable insight, and it is worth stating:

  • The first phase is agreement and authorisation, not technique; the test is founded on the rules before anything is touched.
  • The middle phases build understanding before intrusion: gather intelligence, model the threat, analyse vulnerabilities, so the intrusion is informed and aimed, not blind.
  • The intrusion is phases five and six, bounded and purposeful (verify exploitability, assess impact), not the point in itself.
  • The last phase is the report, the product.

So the structure runs rules, understanding, bounded intrusion, report, and the technical break-in occupies a minority of it. This shape embodies the methodology thesis: the value is in the structure that surrounds the intrusion (authorisation, systematic analysis, and reporting), not in the intrusion alone. A student who can name the seven phases and explain this shape understands professional penetration testing as MU intends.

A worked example, framed defensively

An organisation reviews a proposed penetration test structured on PTES, at concept level, checking each phase is planned.

  • Pre-engagement: scope, rules of engagement, timing and written authorisation are agreed. The organisation confirms this is the foundation and that out-of-bounds systems are named.
  • Intelligence gathering and threat modelling: the tester will map the in-scope systems and model the realistic threats, so the test is aimed at what matters (the organisation's valuable assets).
  • Vulnerability analysis: the tester will systematically identify weaknesses across the taught categories, giving thoroughness.
  • Exploitation and post-exploitation: the tester will confirm which weaknesses are real and assess their impact, bounded by scope and do-no-harm, to evidence risk for the report.
  • Reporting: the deliverable will be a clear, prioritised report, the product the organisation is actually commissioning.
  • The organisation notes that only two of seven phases are the intrusion, and that most of the test's value is in the authorisation, analysis and report around it, confirming the methodology thesis.
munotes.in554

PTES: the Seven Phases

The review checks a professional test against the seven phases, seeing authorisation first and the report last with bounded intrusion between. The organisation is planning a defensive assessment; nothing offensive is detailed.

What beginners get wrong

  • Thinking the test is the exploitation phase. Exploitation is one of seven phases; the test runs from authorisation (phase one) to the report (phase seven), with intrusion a bounded minority.
  • Skipping pre-engagement. The first phase is agreeing scope and authorisation in writing; without it there is no lawful test, so it is the foundation, not a formality.
  • Testing blindly. The middle phases (intelligence, threat modelling, vulnerability analysis) build an informed, aimed picture before intrusion, so the test focuses on what matters.
  • Treating exploitation as the goal. It exists to verify that a weakness is real and reachable, not to cause harm; post-exploitation then assesses impact, bounded by scope.
  • Underrating reporting. The last phase is the product; all the others build toward the clear, prioritised report the client can act on.
  • Ignoring the shape. Rules, understanding, bounded intrusion, report, with intrusion a minority, is the insight the seven phases teach, embodying the methodology thesis.

Quick revision

  • PTES (Penetration Testing Execution Standard) gives seven phases: 1 pre-engagement (scope, rules, written authorisation), 2 intelligence gathering (map the target, in scope), 3 threat modelling (aim the test at realistic risks), 4 vulnerability analysis (systematically identify weaknesses, thoroughness), 5 exploitation (verify which are actually exploitable, bounded), 6 post-exploitation (assess impact, bounded by scope, do no harm), 7 reporting (the clear, prioritised product).
  • The shape: rules, understanding, bounded intrusion, report; the technical break-in is only phases 5 and 6, a minority.
  • The shape embodies the methodology thesis: value is in the structure around the intrusion (authorisation, analysis, report), not the intrusion.

Test yourself

  1. What are the seven phases of PTES, in order?

Pre-engagement interactions, where scope, rules of engagement and written authorisation are agreed; intelligence gathering, where information about the in-scope target is collected; threat modelling, where realistic adversaries and valuable assets are identified to aim the test; vulnerability analysis, where weaknesses are systematically identified; exploitation, where the tester confirms which weaknesses are actually exploitable within bounds; post-exploitation, where the significance of the access is assessed, bounded by scope and do-no-harm; and reporting, where the clear, prioritised account of findings and fixes is delivered. The sequence runs from agreement and authorisation to the report, with the intrusion in the middle.

munotes.in555

PTES: the Seven Phases

  1. Why is pre-engagement the essential first phase?

Because it is where the test is properly scoped and authorised before anything technical happens: the tester and client agree which systems are in and out of bounds, the rules of engagement, the timing and goals, and above all the written authorisation. This phase is where the principle that authorisation is everything lives, so without it there is no lawful test at all; it is the foundation on which the technical phases rest, which is why it comes first and why it is a substantive phase rather than a formality.

  1. Why do the middle phases build understanding before the intrusion?

Because a test aimed by understanding is thorough and focused, whereas a blind intrusion is neither. Intelligence gathering maps the in-scope systems, threat modelling identifies what a realistic attacker would want and the valuable assets so the test is aimed at what matters to this client, and vulnerability analysis systematically identifies weaknesses across the taught categories. Only after this informed picture is built does exploitation confirm which weaknesses are real, so the intrusion is purposeful and comprehensive rather than a scattershot attempt, which is how the method delivers thoroughness.

  1. What is the purpose of the exploitation and post-exploitation phases, and how are they bounded?

Exploitation exists to verify which identified weaknesses are actually exploitable and reachable, confirming that a vulnerability is real rather than merely theoretical, and post-exploitation exists to assess the significance of that access so the report can convey the true impact. Both are bounded by the scope and rules of engagement agreed in pre-engagement and by the do-no-harm discipline: the tester acts only within the authorised systems, does the minimum needed to demonstrate impact, causes no harm, and stops, because the goal is evidence for the report, not exploitation for its own sake.

  1. What does the shape of the seven-phase sequence teach about penetration testing?

The shape runs rules, understanding, bounded intrusion, report: the first phase is agreement and authorisation, the middle phases build an informed picture, the intrusion is only phases five and six and is bounded and purposeful, and the last phase is the report that is the product. It teaches that most of a professional test is not the break-in, and that a test's value lies in the structure surrounding the intrusion, the authorisation, systematic analysis and reporting, rather than in the intrusion itself, which is the methodology thesis made concrete in a recognised standard.

Contents This chapter on its own page

munotes.in556

Chapter One Hundred Twenty-Two

The OWASP Testing Guide

Syllabus topic Module 2, "Penetration Testing Methodology and Reporting: structured testing methodology"

In one line

The OWASP Testing Guide is a comprehensive, categorised checklist for testing web application security: it lists systematically what to test (authentication, session management, input handling, access control, configuration, and more), so a tester covers every category rather than only what occurs to them. It is how the thoroughness the block argued for is achieved for the most common kind of target.

In examination wording: the OWASP Testing Guide is a widely-used methodology providing a structured, categorised set of tests for web application security, organised by area such as authentication, session management, input validation, and access control; its checklist-based approach ensures comprehensive coverage of web-application weaknesses, complementing an overall engagement methodology such as PTES with detailed, systematic web-testing content.

Two methodologies, two levels

A student should see how the OWASP Testing Guide relates to PTES, because they operate at different levels and complement each other:

  • PTES (previous chapter) gives the overall shape of the engagement: the seven phases from authorisation to report, applicable to any kind of test.
  • The OWASP Testing Guide gives the detailed content for one (very common) kind of target: web applications. Within PTES's "vulnerability analysis" and "exploitation" phases, when the target is a web application, the OWASP Testing Guide is the systematic checklist of what to examine.

So they are not competitors; PTES is the frame, and the OWASP Testing Guide fills in the web-specific detail. Since web applications are the most common target, the OWASP Testing Guide is one of the most-used methodologies in practice, which is why MU's methodology topic naturally includes it, and why the whole book's web-security material (the OWASP Top 10, the injection family, session security, access control) culminates here as things a methodology tells you to test.

What the guide provides

The OWASP Testing Guide is, in essence, a comprehensive categorised checklist of web-application security tests, and the examinable content is what kind of thing it organises:

  • It is organised by category of weakness, so that testing proceeds area by area rather than randomly. The categories correspond to the web-security concepts the book has taught, including:
  • Authentication testing (are the login and identity mechanisms sound? the password and authentication chapters).
  • Session management testing (are sessions handled securely? the session-security chapters).
  • Input validation testing (is input handled safely, defending against the injection family? the injection chapters).
  • Authorisation / access control testing (can users reach only what they should? the access-control chapters, OWASP A01).
  • Configuration testing (is the deployment securely configured? the misconfiguration chapters, OWASP A02).
  • and further categories (error handling, cryptography in use, business logic, client-side).
  • For each category, it describes what to test for and what a weakness looks like, so a tester systematically checks each, which is exactly the systematic search that delivers thoroughness.
munotes.in557

The OWASP Testing Guide

The point is not to memorise every category but to understand that the guide turns the book's scattered web-security concepts into an organised checklist a tester works through, so nothing is missed. It is the methodology thesis (thoroughness through structure) applied to web applications.

Why a checklist delivers thoroughness

The chapter's deeper point, tying to the block's thesis, is why a checklist-based methodology is what makes web testing valuable:

  • Web applications have many categories of possible weakness (authentication, sessions, input, access control, configuration, and more), and a real application may be weak in any of them. An ad-hoc tester examines the categories that occur to them and misses the rest.
  • A checklist ensures every category is examined, so the test's coverage is comprehensive by construction, not by the tester's memory. The value, as the methodology chapter argued, is in not missing the weakness that matters, and the checklist is exactly the mechanism that prevents missing categories.
  • It also makes tests consistent (every tester covers the same categories) and comparable (results can be tracked against the same checklist over time), the other methodology virtues.

So the OWASP Testing Guide is the concrete instrument by which web-application testing achieves thoroughness and consistency: a shared, comprehensive checklist. This is why professional web testing follows it (or a similar guide) rather than relying on individual cleverness, and it is the examinable reason the guide matters.

The book's web security, as a test plan

Worth noting as the culmination: the web-security material the book taught across Module I and beyond, the OWASP Top 10, the injection family, session security, access control, misconfiguration, now appears as the content of a test plan. What the book taught as weaknesses to understand and defend becomes, in the OWASP Testing Guide, things a methodology directs a tester to check. So the guide is where the defensive knowledge and the testing method meet: understanding the weakness (the book) and systematically testing for it (the guide) are two sides of the same security competence. A student who has followed the book can read the guide's categories and recognise every one.

A worked example, framed defensively

A team plans a web-application penetration test and uses the OWASP Testing Guide to ensure coverage, at concept level, within an authorised PTES engagement.

  • Within PTES's vulnerability analysis phase, the team adopts the OWASP Testing Guide as the checklist for the web application in scope, so coverage is systematic.
  • They work category by category: authentication (login soundness), session management (secure session handling), input validation (defence against the injection family), access control (users reach only what they should), configuration (secure deployment), and the rest, checking each rather than only the obvious ones.
  • Because the checklist is comprehensive, a weakness in a category they might not have thought of ad hoc (say, a session-management flaw) is examined and found, illustrating thoroughness by construction.
  • The findings feed the risk rating (next chapter) and the report (the product), and because the same checklist is used each time, results are consistent and comparable across tests.
  • The team notes that every category corresponds to something the book taught as a weakness to defend, so their defensive knowledge and their test plan are the same knowledge.
munotes.in558

The OWASP Testing Guide

The team uses the guide to achieve comprehensive, consistent coverage of the authorised web target, feeding an actionable report. The work is a defensive assessment structured by the methodology; nothing offensive is detailed.

What beginners get wrong

  • Seeing PTES and the OWASP Testing Guide as competitors. They are at different levels: PTES frames the engagement, the OWASP Testing Guide is the detailed web-testing checklist within it; they complement each other.
  • Thinking the guide is a list of tricks. It is a categorised checklist of what to test, ensuring coverage; its value is thoroughness by construction, not any individual technique.
  • Missing why a checklist matters. Web apps have many weakness categories, and only a comprehensive checklist ensures every one is examined, so the important weakness is not missed, which is the methodology thesis.
  • Treating the categories as unfamiliar. They correspond to the web-security concepts the book taught (authentication, sessions, input, access control, configuration); the guide organises them into a test plan.
  • Underrating consistency. A shared checklist makes tests consistent and comparable across time and testers, not just thorough.
  • Forgetting the culmination. The guide is where defensive knowledge (understanding weaknesses) and testing method (systematically checking for them) meet; they are two sides of one competence.

Quick revision

  • The OWASP Testing Guide is a comprehensive, categorised checklist for web-application security testing: authentication, session management, input validation, access control, configuration, and more, saying what to test in each.
  • It relates to PTES as detail to frame: PTES gives the seven-phase engagement shape; the OWASP Testing Guide fills the web-specific content within the vulnerability-analysis and exploitation phases. Web apps being the most common target, it is heavily used.
  • Why a checklist: web apps have many weakness categories; a checklist ensures every category is examined, giving thoroughness by construction, plus consistency and comparability. The methodology thesis applied to web testing.
  • Culmination: the book's web-security concepts (OWASP Top 10, injection, sessions, access control) become the content of a test plan; understanding weaknesses and testing for them are two sides of one competence.

Test yourself

  1. What is the OWASP Testing Guide, and how does it relate to PTES?
munotes.in559

The OWASP Testing Guide

The OWASP Testing Guide is a comprehensive, categorised checklist for testing web-application security, organised by area such as authentication, session management, input validation, access control and configuration, saying what to test in each. It relates to PTES as detailed content to overall frame: PTES defines the seven-phase shape of any engagement, from authorisation to report, while the OWASP Testing Guide provides the systematic web-testing checklist used within PTES's vulnerability-analysis and exploitation phases when the target is a web application. They operate at different levels and complement each other rather than competing.

  1. Why does a checklist-based methodology deliver thoroughness for web testing?

Because web applications can be weak in any of many categories, authentication, sessions, input handling, access control, configuration and more, and an ad-hoc tester examines only the categories that occur to them, missing the rest, while an attacker needs only the missed one. A checklist ensures every category is examined by construction rather than by the tester's memory, so coverage is comprehensive and the weakness that matters is not overlooked. This is the methodology thesis, that value lies in not missing the important flaw, applied concretely to web applications through a shared, comprehensive checklist.

  1. How do the guide's categories relate to what the book has taught?

They correspond directly to the web-security concepts taught across the book: authentication testing to the password and authentication chapters, session-management testing to the session-security chapters, input-validation testing to the injection family, access-control testing to the access-control chapters and OWASP A01, and configuration testing to the misconfiguration chapters and OWASP A02, with further categories for error handling, cryptography in use and business logic. So the guide organises the book's scattered web-security material into a systematic test plan, and a student who has followed the book can recognise every category.

  1. Besides thoroughness, what other methodology virtues does the guide provide?

It provides consistency and comparability: because every tester works through the same categories, the test applies the same rigour regardless of who performs it, giving a dependable standard, and because the same checklist is used over time, results can be tracked and compared across tests to see whether weaknesses recur or are fixed. These are the same virtues the methodology chapter identified beyond thoroughness, so the guide delivers all three of thoroughness, consistency and comparability for web-application testing rather than thoroughness alone.

  1. Why is the OWASP Testing Guide described as where defensive knowledge and testing method meet?

Because the web-security material the book taught as weaknesses to understand and defend, the OWASP Top 10, the injection family, session security, access control and misconfiguration, appears in the guide as the things a methodology directs a tester to check. Understanding a weakness in order to defend against it and systematically testing for that same weakness are two sides of the same security competence, so the guide is where they meet: it turns the defensive understanding into an organised test plan, and a defender who knows the weaknesses already knows what the guide tells a tester to examine.

Contents This chapter on its own page

munotes.in560

Chapter One Hundred Twenty-Three

Risk Assessment and Rating

Syllabus topic Module 2, "Penetration Testing Methodology and Reporting: ... risk assessment, reporting"

In one line

Risk combines two questions: how likely is a weakness to be exploited, and how bad would it be if it were (impact). A finding that is both likely and severe is high risk; one that is neither is low. Rating every finding this way lets the tester prioritise, telling the client what to fix first, which is what turns a list of weaknesses into an actionable report.

In examination wording: risk assessment rates each finding by combining the likelihood of exploitation with the impact of a successful exploit, so that findings can be prioritised; a common quantified expression is the CVSS score, and the purpose of rating is to produce a prioritised, actionable set of findings that directs the client's remediation effort to the most serious weaknesses first.

Why rating is necessary

A thorough test (the methodology of the previous chapters) finds many weaknesses, often more than a client can fix immediately. If the report simply listed them all as equal, the client would not know where to start, and might spend effort on a minor issue while a critical one waited. So the tester must rate each finding by its risk, so the report can say what matters most, and remediation effort goes where it counts.

This is the bridge from finding weaknesses to helping the client: thoroughness finds everything; rating prioritises it; the report communicates the priority. Without rating, thoroughness is almost a burden (a huge undifferentiated list); with rating, it becomes an actionable plan. So risk rating is what makes a thorough test usable, which is why the block treats it as a distinct skill.

The core idea: likelihood and impact

The examinable heart of risk is that it combines two independent questions, and a student should hold them apart:

  • Likelihood: how likely is this weakness to be exploited? This depends on how easy the weakness is to exploit (does it need deep skill or is it trivial?), how exposed it is (internet-facing or deep inside?), and how attractive it is to attackers. A trivially-exploitable, internet-facing weakness is high likelihood; one needing rare access and deep skill is low.
  • Impact: how bad would it be if it were exploited? This depends on what the exploitation would cost the organisation, in terms of the CIA triad the book began with: loss of confidentiality (data exposed), integrity (data altered), or availability (systems down), and the business consequences. Exposure of the whole customer database is high impact; a minor information leak is low.

Risk combines the two. A weakness that is both likely to be exploited and severe in impact is high risk and must be fixed first; one that is unlikely and minor is low risk and can wait. The two questions are independent, so all four combinations occur, and the interesting cases are the mixed ones:

munotes.in561

Risk Assessment and Rating

  • Likely but low impact (easy to exploit, little harm): moderate; fix, but not first.
  • Unlikely but high impact (hard to exploit, catastrophic if done): moderate to high; the severity means it cannot be ignored despite the low likelihood.

So rating each finding means asking both questions and combining them, and the combination, not either alone, is the risk. This is why a hard-to-exploit but catastrophic weakness still rates seriously, and a trivial-to-exploit but harmless one does not dominate.

Connecting to CVSS

The book already taught a quantified version of exactly this, the CVSS score (the vulnerability-scoring chapter), and risk rating is where it is used. CVSS produces a number (0.0 to 10.0) and a severity band (low, medium, high, critical) for a vulnerability by combining factors that amount to how easy it is to exploit and how much impact it has, the same two questions. So:

  • CVSS is a standardised way to express the likelihood-and-impact rating for a known vulnerability, giving a comparable number and severity band.
  • A tester uses CVSS scores where they apply (for identified known vulnerabilities) as part of rating, and applies the same likelihood-and-impact reasoning to findings that are not simply a known CVE.

The connection to hold: CVSS is the quantified form of the likelihood-and-impact idea, so the risk rating in a report and the CVSS scores the book taught are the same reasoning, one as structured judgement and one as a standard number. A student should recognise that the CVSS chapter was teaching the measurement that this chapter uses to prioritise.

From rating to priority

Rating produces, for each finding, a risk level (commonly critical, high, medium, low), and the tester orders the findings by risk so the report leads with the most serious. This ordering is the actionable output: the client reads it as "fix the criticals now, then the highs, then the rest", so their limited effort goes to the greatest risk reduction first. The report chapter builds on this: a good report presents findings in priority order with their risk ratings, so the client can act rationally. So risk rating is the step that converts thorough findings into a prioritised plan, which is the whole purpose of assessing risk.

A worked example, framed defensively

A tester rates the findings of an authorised test to prioritise the report, at concept level.

  • Finding A: a trivially-exploitable, internet-facing flaw exposing customer data. Likelihood high (easy, exposed), impact high (confidentiality of customer data). Risk: critical, fix first. Its CVSS score, computed as the book taught, lands in the critical band, confirming the judgement.
  • Finding B: a flaw that would fully compromise a system but requires rare internal access and deep skill. Likelihood low, impact high. Risk: high (the severity keeps it serious despite low likelihood), fix soon.
  • Finding C: an easily-exploitable issue that leaks only trivial, non-sensitive information. Likelihood high, impact low. Risk: low to medium, fix but not urgently.
  • Finding D: a hard-to-exploit issue of minor impact. Likelihood low, impact low. Risk: low, fix when convenient.
  • The tester orders the report A, B, C, D by risk, so the client fixes the critical customer-data exposure first. The rating, not the order of discovery, sets the priority.
munotes.in562

Risk Assessment and Rating

The tester turns thorough findings into a prioritised, actionable report by rating each on likelihood and impact, using CVSS where it applies. The work is assessment and communication; nothing offensive is described.

What beginners get wrong

  • Listing findings as equal. A client cannot fix everything at once, so findings must be rated and ordered by risk, or the report is an undifferentiated burden.
  • Confusing likelihood with impact. They are independent questions, how likely to be exploited and how bad if exploited; risk is their combination, not either alone.
  • Ignoring high-impact, low-likelihood findings. A hard-to-exploit but catastrophic weakness still rates seriously, because the severity means it cannot be ignored; likelihood alone does not decide.
  • Letting trivial-but-easy findings dominate. An easily-exploited but harmless issue is not high risk; impact must be weighed, not just ease.
  • Treating CVSS as unrelated. CVSS is the quantified form of the likelihood-and-impact idea, giving a standard number and severity band; it is the measurement this rating uses.
  • Forgetting the purpose. Rating exists to prioritise, turning thorough findings into an ordered, actionable plan the client can follow, which is the point of the report.

Quick revision

  • A thorough test finds many weaknesses; a client cannot fix all at once, so the tester rates each by risk to prioritise. Rating turns thoroughness into an actionable plan.
  • Risk = likelihood combined with impact, two independent questions:
  • Likelihood: how likely to be exploited (ease, exposure, attractiveness).
  • Impact: how bad if exploited (confidentiality, integrity, availability, business cost).
  • All four combinations occur; high+high = critical (fix first), low+low = low; a high-impact, low-likelihood finding still rates seriously; an easy-but-harmless one does not dominate.
  • CVSS is the quantified form of likelihood-and-impact (0.0 to 10.0, low/medium/high/critical), used where known vulnerabilities apply; the CVSS chapter taught this measurement.
  • Output: findings in priority order (critical, high, medium, low) so the client fixes the greatest risk first, feeding the report.

Test yourself

  1. Why must a tester rate findings by risk rather than list them equally?
munotes.in563

Risk Assessment and Rating

Because a thorough test finds many weaknesses, often more than a client can fix immediately, and if all were listed as equal the client would not know where to start and might fix a minor issue while a critical one waited. Rating each finding by risk lets the report say what matters most, so limited remediation effort goes to the most serious weaknesses first. Rating is the bridge from finding weaknesses to helping the client: thoroughness finds everything, rating prioritises it, and the report communicates the priority, turning a large undifferentiated list into an actionable plan.

  1. What two independent questions combine to give risk, and why must they be held apart?

Likelihood, how likely the weakness is to be exploited, which depends on how easy it is to exploit, how exposed it is, and how attractive it is to attackers; and impact, how bad it would be if exploited, which depends on the loss of confidentiality, integrity or availability and the business consequences. They must be held apart because they are independent, so all four combinations occur, and risk is their combination rather than either alone; treating likelihood or impact by itself as the risk misjudges the mixed cases, such as a catastrophic but hard-to-exploit weakness.

  1. How should a high-impact, low-likelihood finding be rated, and why?

It should still be rated seriously, typically high, rather than dismissed because it is hard to exploit, because the severity of its impact means the organisation cannot afford to ignore it: if the unlikely exploitation did occur, the consequences would be grave. Risk is the combination of likelihood and impact, so a low likelihood does not cancel a high impact; it moderates it, leaving a finding that remains important. This is why rating asks both questions and combines them rather than letting likelihood alone decide.

  1. How does CVSS relate to the likelihood-and-impact idea?

CVSS is the quantified, standardised form of the same idea: it produces a number from 0.0 to 10.0 and a severity band of low, medium, high or critical by combining factors that amount to how easy a vulnerability is to exploit and how much impact it has, which are precisely the likelihood and impact questions. So a tester uses CVSS scores where they apply, for identified known vulnerabilities, as part of rating, and applies the same likelihood-and-impact reasoning to findings that are not a simple known vulnerability; the CVSS chapter taught the measurement that risk rating uses to prioritise.

  1. How does risk rating turn a thorough test into an actionable report?

Rating assigns each finding a risk level, commonly critical, high, medium or low, and the tester orders the findings by risk so the report leads with the most serious. This ordering is the actionable output: the client reads it as fix the criticals now, then the highs, then the rest, so their limited effort achieves the greatest risk reduction first. Without rating, a thorough test's many findings are an undifferentiated burden; with rating, they become a prioritised plan, which is why risk assessment is the step that makes thoroughness usable and feeds directly into the report.

Contents This chapter on its own page

munotes.in564

Chapter One Hundred Twenty-Four

The Penetration-Test Report

Syllabus topic Module 2, "Penetration Testing Methodology and Reporting: ... reporting"

In one line

A penetration-test report has two audiences and so two parts: an executive summary (for management, non-technical, conveying the overall risk and what it means for the business) and detailed findings (for the technical team, each finding with its risk rating, a clear description, the evidence, the impact, and how to fix it). The report is written to be understood and acted upon, because it is the product of the test.

In examination wording: a penetration-test report comprises an executive summary that communicates the overall security posture and business risk to non-technical decision-makers, and a detailed technical section that documents each finding with its risk rating, description, evidence, impact, and remediation guidance; the report is structured for its two audiences so that the organisation can understand the risk and act to remediate it.

The report is the product

The methodology chapter established it and the block has repeated it: the report is the product of the test. Everything before, the authorisation, the systematic testing, the risk rating, exists to produce a report that lets the client improve their security. So the report is not an afterthought or a formality; it is the deliverable, and writing it well is as much a professional skill as the testing. A test that finds much but reports it poorly has largely failed, because the client cannot act on what they cannot understand. This chapter gives the structure that makes a report understood and actionable.

Two audiences, two parts

The central idea of report structure, and the examinable one, is that a report has two very different audiences, who need different things, so it has two parts:

The executive summary, for decision-makers (management). These readers are not technical and need to understand the business risk, not the technical detail. The executive summary tells them, in plain language: what was tested, what the overall security posture is, what the most serious risks mean for the business (the potential consequences), and what should be done at a high level. It must be understandable to someone who will decide on budget and priorities without reading the technical section. Its job is to convey how serious things are and why it matters, so leadership can decide to act.

The detailed findings, for the technical team (who will fix them). These readers are technical and need enough detail to understand and fix each weakness. For each finding, the detailed section gives:

  • A clear title and its risk rating (critical, high, medium, low, from the rating chapter), so its priority is immediate.
  • A description of the weakness: what it is, where it is, in enough technical detail to understand it.
  • The evidence: what the test found that demonstrates the weakness is real (so it is credible and reproducible), presented responsibly.
  • The impact: what could happen if it were exploited (the impact half of risk), so the team understands why it matters.
  • The remediation: how to fix it, concretely, which is the most important part for the technical reader, because the point is to get it fixed.
munotes.in565

The Penetration-Test Report

So the detailed findings are written for action: each is a self-contained, prioritised, fixable item. The two parts together serve the whole organisation: the summary gets leadership to act, and the findings tell the technical team what to do.

What makes a finding well-written

Since the findings are where remediation happens, the qualities of a well-written finding are examinable, and they follow from its purpose:

  • Clear: understandable by the technical reader, unambiguous about what the weakness is and where.
  • Evidenced: backed by what the test found, so it is credible and can be confirmed, but presented responsibly (enough to demonstrate and fix, not a weaponised recipe).
  • Prioritised: carrying its risk rating, so the team knows where it sits.
  • Actionable: with concrete remediation, so the reader knows what to do, not just what is wrong.
  • Accurate and honest: neither inflated nor understated, reporting what was actually found (the integrity obligation).

A finding with these qualities gets fixed; one lacking them (vague, unevidenced, unrated, or with no remediation) does not help the client, however real the weakness. So writing findings well is a core professional skill, not clerical work.

Responsible reporting

The report contains the organisation's weaknesses, so it is sensitive, and the reporting obligations from the ethics chapter apply directly:

  • Confidentiality and secure delivery. The report is delivered securely to the client and treated as confidential; a document listing an organisation's exploitable weaknesses is dangerous in the wrong hands, so it is not emailed carelessly, published, or shared beyond those agreed.
  • Responsible detail. Findings include enough to understand and fix the weakness, presented responsibly for the client's remediation, not as a ready-to-use attack guide for a wider audience.
  • Accuracy. Findings are honest and precise, so the client's decisions rest on the truth.

So the report is written and handled with the care its sensitivity demands, which is part of the professionalism the block has stressed throughout.

A worked example, framed defensively

A tester structures the report of an authorised test for its two audiences, at concept level.

  • The executive summary tells management, in plain language, that the test found the overall security posture to be (say) mixed, with a small number of serious risks, chiefly a critical exposure of customer data, that could mean regulatory and reputational harm, and recommends prioritising those fixes. A non-technical leader can read this and decide to act.
  • The detailed findings give the technical team each weakness: the critical customer-data exposure first, with its rating, a clear description of what and where, responsible evidence that it is real, the impact (customer data exposed), and concrete remediation (the specific fix). Then the high, medium and low findings in order, each self-contained and actionable.
  • The report is delivered securely and confidentially, and the findings are written responsibly (enough to fix, not a weaponised recipe) and accurately.
  • The organisation acts: leadership prioritises from the summary, the technical team fixes from the findings, and the test achieves its purpose, improved security.
munotes.in566

The Penetration-Test Report

The report serves both audiences, turning the test into action, and is handled with the care its sensitivity demands. The tester communicates findings to defend the client; nothing offensive is packaged.

What beginners get wrong

  • Treating the report as an afterthought. It is the product of the test; writing it well is as much a professional skill as testing, and a poorly-reported test has largely failed.
  • Writing for one audience. The report has two: management (executive summary, business risk, non-technical) and the technical team (detailed findings, how to fix); each needs different content.
  • Making the executive summary technical. Decision-makers need the business risk and what to do in plain language, so they can prioritise budget and effort without the detail.
  • Writing findings that only describe the problem. A finding must also be evidenced, rated, and above all actionable (concrete remediation), because the point is to get it fixed.
  • Handling the report carelessly. It lists the organisation's weaknesses and is sensitive; it is delivered securely and confidentially, and findings are responsibly detailed, not attack recipes.
  • Inflating or hiding findings. The report must be accurate and honest, so the client's decisions rest on the truth.

Quick revision

  • The report is the product; writing it well is a core professional skill. Two audiences, two parts:
  • Executive summary (management, non-technical): overall posture and business risk, what it means, what to do at a high level, so leadership can decide to act.
  • Detailed findings (technical team, who fix them): per finding, a title + risk rating, description, evidence (responsible), impact, and remediation (how to fix, the key part).
  • A well-written finding is clear, evidenced, prioritised, actionable, accurate/honest.
  • Responsible reporting: confidential and securely delivered, responsibly detailed (enough to fix, not an attack recipe), accurate. The report lists weaknesses, so it is sensitive.

Test yourself

  1. Why is the penetration-test report considered the product of the test?

Because everything before it, the authorisation, the systematic testing, and the risk rating, exists to produce a report that lets the client improve their security, which is the actual purpose of commissioning a test. The client is not paying to be broken into but to receive a clear, prioritised account of their weaknesses and how to fix them, so the report is the deliverable through which the test's value is realised. A test that finds much but reports it poorly has largely failed, because the client cannot act on what they cannot understand, which is why writing the report well is as much a professional skill as the testing.

munotes.in567

The Penetration-Test Report

  1. Why does a report have two parts, and who is each for?

Because it has two very different audiences who need different things. The executive summary is for management and other non-technical decision-makers, conveying the overall security posture and what the most serious risks mean for the business in plain language, so leadership can decide on budget and priorities without reading the technical detail. The detailed findings are for the technical team who will fix the weaknesses, giving each finding in enough technical depth to understand and remediate it. Serving both audiences lets the whole organisation act: the summary gets leadership to act, and the findings tell the technical team what to do.

  1. What should each detailed finding contain, and why is remediation the key part?

Each finding should contain a clear title and its risk rating so its priority is immediate, a description of what the weakness is and where, the evidence that it is real presented responsibly, the impact of exploitation so its seriousness is understood, and concrete remediation guidance on how to fix it. Remediation is the key part because the purpose of the report is to get the weakness fixed, so a finding that only describes the problem without saying how to address it leaves the technical reader knowing what is wrong but not what to do, which does not improve the client's security.

  1. What qualities make a finding well-written, and why do they matter?

A well-written finding is clear, so the technical reader understands unambiguously what the weakness is and where; evidenced, so it is credible and confirmable, but responsibly presented; prioritised, carrying its risk rating so its place is known; actionable, with concrete remediation so the reader knows what to do; and accurate and honest, neither inflated nor understated. They matter because a finding with these qualities gets fixed, while one that is vague, unevidenced, unrated, or without remediation does not help the client however real the underlying weakness, so writing findings well is a core professional skill rather than clerical work.

  1. Why must a penetration-test report be handled with particular care, and how?

Because it contains the organisation's exploitable weaknesses, so it is highly sensitive and dangerous in the wrong hands. It is handled by delivering it securely to the client and treating it as confidential, not emailing it carelessly, publishing it, or sharing it beyond those agreed; by keeping the findings responsibly detailed, enough to understand and fix each weakness but not a ready-to-use attack guide for a wider audience; and by ensuring accuracy so the client's decisions rest on the truth. This care reflects the reporting and confidentiality obligations of professional practice that the block has stressed throughout.

Contents This chapter on its own page

munotes.in568

Chapter One Hundred Twenty-Five

A Worked Specimen Report

Syllabus topic Module 2, "Penetration Testing Methodology and Reporting: ... reporting"

In one line

This chapter is a short, illustrative specimen of a penetration-test report, fictional and responsibly written, so the student can see the structure in practice: a plain-language executive summary followed by detailed findings, each with a title, risk rating, description, impact, and remediation, in priority order. It models what the previous chapters described.

In examination wording: a specimen penetration-test report demonstrates the standard structure in practice, comprising a non-technical executive summary of overall risk and prioritised, self-contained technical findings each stating a risk rating, description, impact, and remediation; studying a worked specimen clarifies how the reporting principles are applied.

How to read this specimen

The specimen below is fictional (an invented client and findings) and deliberately short (a real report has many findings); its purpose is to show the shape and tone, not to be complete. It is written responsibly, as the block requires: each finding describes the weakness clearly enough to understand and fix, and states its impact and remediation, but does not include a usable attack (no exploit strings, no step-by-step intrusion), which is exactly how a professional report balances usefulness against responsible detail. As you read, notice how the executive summary speaks to management and the findings speak to the technical team, and how each finding carries the qualities the previous chapter named: clear, evidenced (described responsibly), prioritised, actionable, honest.

Specimen: executive summary

Penetration Test Report, Example Retail Web Application, Executive Summary

Prepared for: the management of Example Retail. Confidential.

We were authorised to assess the security of the Example Retail customer web application between the agreed dates, within the agreed scope. This summary is for decision-makers; the detailed findings follow for the technical team.

Overall, the application's security is mixed. The core platform is reasonably maintained, but the test found two serious weaknesses that require prompt attention, along with several lower-risk issues.

The most serious finding is that customer personal data could be accessed without proper authorisation. In business terms, this means customer records could be exposed, which would carry legal, regulatory, and reputational consequences. We rate this critical and recommend it be fixed as a priority.

The second serious finding is that the login system does not adequately limit repeated password attempts, making customer accounts more vulnerable to being guessed into. We rate this high.

The remaining issues are medium and low risk and should be addressed in the normal course of maintenance. None of the findings suggests the application has already been compromised.

Recommended priorities: fix the critical data-access issue immediately, address the login weakness soon, and schedule the remaining items. We would be glad to retest once the fixes are in place.

Notice: it is plain language, conveys business risk (legal, regulatory, reputational), gives an overall posture and a clear priority, and never assumes technical knowledge. A manager can read it and decide to act.

munotes.in569

A Worked Specimen Report

Specimen: detailed findings (two, illustrative)

Detailed Findings (technical section; findings in priority order)

---

Finding 1: Customer data reachable without proper authorisation

Risk: Critical

Description. A part of the application that returns customer records did not properly check that the requesting user was authorised to see the records requested. As a result, a logged-in user could reach records belonging to other customers by altering an ordinary request, because the application relied on the interface hiding the other records rather than on the server enforcing the authorisation. This is a broken-access-control weakness (the server must enforce authorisation on every request).

Evidence. During testing, acting only within the authorised scope and using test accounts, we confirmed that a request for one test account could return data belonging to another test account. We did not access any real customer data.

Impact. If exploited, customer personal data could be exposed to other users, with legal, regulatory, and reputational consequences. This is the most serious finding.

Remediation. Enforce authorisation on the server for every request that returns customer data: check that the authenticated user is entitled to the specific records requested, rather than relying on the interface to limit what is shown. Review related endpoints for the same pattern.

---

Finding 2: Login does not limit repeated password attempts

Risk: High

Description. The login system did not adequately limit the number of password attempts against an account, so an attacker could try many passwords against a customer account (an online guessing attack), which is far more feasible when attempts are unlimited.

Evidence. Within scope and using a test account, we confirmed that repeated login attempts were not rate-limited or locked out after many failures.

Impact. Customer accounts with weak or reused passwords are more likely to be guessed into, leading to account takeover.

Remediation. Limit repeated failed login attempts (for example, progressive delays or temporary lockout after a threshold), and support additional protections such as multi-factor authentication. Combined with encouraging strong passwords, this makes online guessing infeasible.

Notice each finding: a title and risk rating (priority immediate), a clear description (what and where, in understandable terms), responsible evidence (confirmed with test accounts, no real data, no attack recipe), the impact (why it matters), and concrete remediation (what to do). Each is self-contained and actionable, and they are in priority order (critical before high).

What the specimen models

The specimen is worth studying because it models, concretely, the block's teaching:

  • Two audiences, two registers: the summary is non-technical and business-focused; the findings are technical and fix-focused. The same test, told two ways for two readers.
  • Priority throughout: the summary leads with the critical issue, the findings are ordered by risk, so the client acts in the right order.
  • Responsible detail: findings describe the weakness and its fix (defensive, actionable) without a usable attack (no exploit strings, no intrusion steps), the balance the ethics chapter required.
  • The book's concepts as findings: the two findings are broken access control (server-side authorisation) and weak login rate-limiting (online guessing), exactly the defensive lessons the book taught, now expressed as report findings with remediation.
munotes.in570

A Worked Specimen Report

So the specimen is the block's principles in practice, and a student who can read it and see why each part is as it is understands professional reporting. Writing findings like these, clear, responsible, prioritised, actionable, is the skill the block builds toward.

A worked example, framed defensively

A student critiques a poorly-written finding by comparison with the specimen, at concept level.

  • A poor finding reads only: "Login is insecure, we got in." It has no risk rating (no priority), a vague description (what is insecure?), no responsible evidence (or, conversely, might irresponsibly include a working attack), no clear impact, and no remediation (what should they do?). The technical team cannot act on it.
  • Compared with specimen Finding 2, which states the rating (high), describes the weakness clearly (unlimited password attempts), evidences it responsibly (confirmed with a test account, rate-limiting absent), gives the impact (account takeover), and the remediation (limit attempts, support multi-factor), the difference is stark: the specimen is actionable, the poor finding is not.
  • The student concludes that a good finding is defined by the qualities the block named, and that the specimen shows how to meet them.

The critique uses the specimen as the model of a well-written, responsible finding, reinforcing the report qualities. The work is about communicating findings to defend a client; nothing offensive is produced.

What beginners get wrong

  • Thinking a specimen must be complete. This one is short and illustrative, to show shape and tone; a real report has many findings, but the structure is the same.
  • Writing findings as attack recipes. The specimen describes each weakness and its fix without a usable attack (no exploit strings, no intrusion steps); responsible detail is enough to understand and remediate, not to attack.
  • Making the summary technical. The specimen summary is plain-language and business-focused (legal, regulatory, reputational), for decision-makers, not the technical detail.
  • Omitting remediation or rating. Each specimen finding has a risk rating and concrete remediation; without them a finding is not actionable, as the poor-finding critique shows.
  • Ignoring priority order. The specimen leads with the critical finding; ordering by risk is what makes the report actionable.
  • Missing that the findings are the book's concepts. Broken access control and login rate-limiting are the defensive lessons the book taught, here as report findings; reporting and defending are the same knowledge.
munotes.in571

A Worked Specimen Report

Quick revision

  • This chapter is a short, fictional, responsibly-written specimen showing the report structure in practice: a plain-language executive summary (overall posture, business risk, priorities) and detailed findings in priority order.
  • Each specimen finding models the qualities: title + risk rating, clear description, responsible evidence (test accounts, no real data, no attack recipe), impact, remediation. Self-contained and actionable.
  • It models the block: two audiences/two registers, priority throughout, responsible detail (fix, not attack), and the book's concepts as findings (broken access control, login rate-limiting).
  • A good finding is clear, responsibly evidenced, prioritised, actionable, honest; a poor finding (vague, unrated, no remediation, or an attack recipe) cannot be acted on.

Test yourself

  1. What is the purpose of studying a worked specimen report, and why is this one short and fictional?

Its purpose is to show the report structure in practice, so the student sees how an executive summary and detailed findings actually read rather than only knowing the structure in the abstract. It is short and fictional because its aim is to convey the shape and tone, not to be a complete report: a real report has many findings, but the structure, a plain-language summary for management and prioritised, self-contained technical findings, is the same, and a brief invented example shows that structure clearly without the length or the sensitivity of a real client's weaknesses.

  1. How does the specimen executive summary differ in register from the detailed findings, and why?

The executive summary is written in plain, non-technical language focused on business risk, the overall security posture, what the serious findings would mean in legal, regulatory and reputational terms, and the recommended priorities, so that a manager can understand and decide to act without technical knowledge. The detailed findings are written in technical language focused on fixing, giving each weakness's description, evidence, impact and remediation for the team that will address it. The registers differ because the two audiences differ: the same test is told two ways so that both leadership and the technical team can act on it.

  1. How does the specimen keep its findings responsible, and why does that matter?

Each specimen finding describes the weakness clearly enough to understand and fix it and states its impact and remediation, but does not include a usable attack: no exploit strings and no step-by-step intrusion, and the evidence notes only that the weakness was confirmed with test accounts without accessing real data. This matters because the report lists the organisation's weaknesses and is sensitive, so it must give the technical team enough to remediate without becoming a ready-to-use attack guide, which is the balance between usefulness and responsible detail that the ethics chapter required.

munotes.in572

A Worked Specimen Report

  1. What qualities of a well-written finding does specimen Finding 1 demonstrate?

It demonstrates all the qualities the report chapter named: a clear title and a risk rating (critical) so its priority is immediate; a clear description of what the weakness is and where, explaining that the server did not enforce authorisation and relied on the interface to hide records; responsible evidence that it was confirmed within scope using test accounts with no real data accessed; the impact, that customer personal data could be exposed with legal, regulatory and reputational consequences; and concrete remediation, to enforce authorisation on the server for every request and review related endpoints. It is clear, responsibly evidenced, prioritised, actionable and honest.

  1. Why are the specimen's findings described as the book's concepts expressed as report findings?

Because the two findings are exactly defensive lessons the book taught: broken access control, addressed by enforcing authorisation on the server for every request rather than relying on the interface, and weak protection against online password guessing, addressed by limiting repeated login attempts and supporting multi-factor authentication. In the report they appear as findings with impact and remediation, which shows that understanding a weakness in order to defend against it and reporting that weakness for a client to fix are the same knowledge, so a defender who has learned the book's concepts already knows what such findings should say.

Contents This chapter on its own page

munotes.in573

Chapter One Hundred Twenty-Six

Retesting and Closing the Engagement

Syllabus topic Module 2, "Penetration Testing Methodology and Reporting: ... reporting" (engagement closure)

In one line

A test is not finished at the report. The client fixes the findings, then a retest confirms each fix actually works (a fix believed done but not verified is not a fix). Then the engagement is closed: the sensitive test material and report are handled and disposed of securely, and the work is formally concluded. Verification and secure closure complete the professional test.

In examination wording: after the report is delivered, the client remediates the findings and the tester conducts a retest to verify that each remediation is effective, since an unverified fix cannot be assumed to work; the engagement is then formally closed, with the test's sensitive artefacts and the report handled and disposed of securely according to the agreement, completing the professional engagement.

The test is not finished at the report

It is natural to think the report is the end, since it is the product, but a professional engagement has two more essential steps, and stating them is the chapter's point: the fixes must be verified, and the engagement must be closed properly. The report tells the client what to fix; but until the fixes are made and confirmed to work, the client's security has not actually improved, it has only been assessed. So the engagement completes with retesting (confirming the fixes) and closure (handling the sensitive material and concluding formally). A test that stops at the report leaves the loop open; verification and closure close it.

Retesting: confirming the fixes work

After the client has had time to remediate the findings, the tester conducts a retest: examining each fixed finding again to confirm the remediation actually works. This step is essential for a reason the book has taught throughout, in the defences, the memory protections, the configuration chapters: a fix believed done is not a fix confirmed done. A remediation can be:

  • Incomplete: it addressed the finding in one place but not everywhere the weakness existed (the specimen's "review related endpoints" caution).
  • Incorrect: it did not actually close the weakness, or closed it in a way that can be bypassed.
  • Regressive: it fixed the finding but introduced a new problem.

Only a retest distinguishes a real fix from a believed one, so the retest verifies that each finding is genuinely resolved. This is the same principle as the whole book's insistence on verification over assumption: you confirm by checking, not by believing. The retest produces an updated statement, each finding now confirmed fixed, still open, or partially fixed, so the client knows their true remaining risk.

The retest is why the specimen report offered "we would be glad to retest once the fixes are in place": the engagement's value is completed by confirming the improvements are real, turning "we told you what to fix" into "we confirmed you fixed it."

munotes.in574

Retesting and Closing the Engagement

Closing the engagement securely

When the findings are fixed and verified, the engagement is formally closed, and closure has a security dimension the book's principles demand:

  • Handle and dispose of sensitive material securely. During the test the tester accumulated sensitive information: notes, evidence, any test data, and the report itself, all of which describe the client's weaknesses. On closure, this material is handled per the agreement: retained securely only as agreed (for example for a defined period), and otherwise securely disposed of, so that a document detailing the client's vulnerabilities does not linger to be exposed later. This is the data-minimisation and confidentiality principle applied to the tester's own artefacts.
  • Remove anything left for the test. Anything the test set up (test accounts, any agreed changes) is removed, leaving the client's systems as they were, per the do-no-harm and reversibility discipline.
  • Formal conclusion. The engagement is concluded formally: confirmation that the work is complete, the final (retested) status delivered, and the relationship closed cleanly, with the client holding an accurate picture of their now-improved security.

So closure is not merely administrative; it is where the tester applies the book's own confidentiality and minimisation principles to the sensitive material the test produced, ensuring the test that improved the client's security does not itself become a liability.

The book, concluded

This is the final chapter, so it returns to the principle that has governed the whole book, because the methodology block is where that principle becomes professional practice. The book taught how a great many attacks work, and it taught every one with its defence, and under one governing idea: security capability is neutral, and its use is defined by authorisation and conduct. The penetration-testing blocks made that idea concrete, an authorised, scoped, bounded, documented, verified, securely-closed engagement that uses the understanding of attacks entirely for the client's benefit, to find and fix weaknesses before a real attacker does.

So the book ends where it began, with the law and ethics: the first legal chapters said unauthorised access is an offence and the student's knowledge must serve defence; the last methodology chapters show what that service looks like in practice, a professional test that is authorised, thorough, honest, and closed with care. The defensive understanding the book built, of the injection family, of access control, of cryptography, of malware, of wireless security, and the rest, is the same understanding a professional tester uses to help a client, and a defender uses to protect a system. Understanding attacks to defend against them, always under authorisation and for the owner's benefit, is the whole of ethical hacking, and it is where the book concludes.

munotes.in575

Retesting and Closing the Engagement

A worked example, framed defensively

An engagement completes through retesting and secure closure, at concept level.

  • The client remediates the report's findings, including the critical data-access issue and the high login issue. After an agreed period, the tester retests.
  • The retest confirms the critical data-access issue is genuinely fixed (server-side authorisation now enforced, and the related endpoints checked too). The login issue is partially fixed (rate-limiting added, but the tester notes multi-factor authentication is not yet in place), so the client learns their true remaining risk. The retest turned believed fixes into confirmed status.
  • On closure, the tester securely disposes of the sensitive test artefacts and handles the report per the agreement, so the document of the client's weaknesses does not linger, and removes the test accounts, leaving the systems as found.
  • The engagement is formally concluded: the client holds an accurate, retested picture of their improved security, and the tester has applied confidentiality and minimisation to the test's own material.

The engagement completes by verifying the fixes and closing securely, so the client's security is genuinely improved and the test leaves no liability behind. The whole engagement served the client's defence under authorisation, which is the book's governing idea in practice.

What beginners get wrong

  • Thinking the test ends at the report. It ends at verified fixes and secure closure; the report tells the client what to fix, but only a retest confirms their security actually improved.
  • Assuming a fix works because it was made. A fix believed done is not confirmed done; it may be incomplete, incorrect, or regressive, so a retest verifies it, the book's verification-over-assumption principle.
  • Skipping the retest. Without it, the client does not know their true remaining risk; the retest turns "we told you what to fix" into "we confirmed you fixed it."
  • Treating closure as mere admin. It has a security dimension: the sensitive test artefacts and report are handled and securely disposed of per the agreement, applying confidentiality and minimisation to the tester's own material.
  • Leaving test artefacts behind. Anything set up for the test (test accounts, agreed changes) is removed, leaving the systems as found, per do-no-harm and reversibility.
  • Missing the book's arc. The engagement embodies the governing idea: capability is neutral, and understanding attacks serves defence under authorisation and for the owner's benefit.

Quick revision

  • A test is not finished at the report. Two more steps complete it:
  • Retest: after the client remediates, the tester re-examines each fixed finding to confirm the fix works. A fix believed done is not confirmed done; remediations can be incomplete, incorrect, or regressive. The retest verifies, giving the client their true remaining risk.
  • Secure closure: handle and securely dispose of the sensitive test artefacts and the report per the agreement (a document of the client's weaknesses must not linger); remove anything set up for the test (systems left as found); formally conclude.
  • Closure applies the book's own confidentiality and minimisation principles to the test's material, so the test does not become a liability.
  • The book concludes: security capability is neutral; understanding attacks serves defence, always under authorisation and for the owner's benefit, which the professional engagement, authorised, thorough, honest, verified, securely closed, embodies.
munotes.in576

Retesting and Closing the Engagement

Test yourself

  1. Why is a penetration test not finished when the report is delivered?

Because the report only tells the client what to fix; until the fixes are made and confirmed to work, the client's security has been assessed but not actually improved. A professional engagement therefore has two more essential steps: retesting, to verify that the client's remediations genuinely resolve the findings, and secure closure, to handle and dispose of the test's sensitive material and conclude formally. A test that stops at the report leaves the loop open, whereas verification and closure complete it, so the engagement finishes at confirmed fixes and secure closure, not at the report.

  1. What is a retest, and why is it essential?

A retest is the tester's re-examination of each fixed finding, after the client has had time to remediate, to confirm that the remediation actually works. It is essential because a fix believed done is not a fix confirmed done: a remediation can be incomplete, addressing the weakness in one place but not everywhere it existed; incorrect, not truly closing the weakness or closing it in a bypassable way; or regressive, fixing the finding but introducing a new problem. Only a retest distinguishes a real fix from a believed one, giving the client their true remaining risk, which applies the book's principle of verification over assumption.

  1. What are the possible outcomes of a retest, and what does the client learn?

For each finding, the retest can confirm it is genuinely fixed, find it still open because the remediation did not work, or find it partially fixed where some but not all of the weakness was addressed. The client learns their true remaining risk: which findings are now resolved and which still need work, so their picture of their security is accurate rather than assumed. This turns the engagement's value from telling the client what to fix into confirming what they actually fixed, which is why the specimen report offered to retest once the fixes were in place.

  1. Why does closing the engagement have a security dimension, and what does secure closure involve?
munotes.in577

Retesting and Closing the Engagement

Because during the test the tester accumulated sensitive information, notes, evidence, test data, and the report itself, all describing the client's weaknesses, so this material is a liability if it lingers or is exposed. Secure closure involves handling and disposing of that material per the agreement, retaining it securely only as agreed and otherwise securely destroying it, so a document of the client's vulnerabilities does not remain to be exposed later; removing anything set up for the test, such as test accounts, so the systems are left as found; and formally concluding with the client holding an accurate retested picture. It applies the book's own confidentiality and minimisation principles to the test's artefacts.

  1. How does the closing of the engagement embody the governing idea of the whole book?

The book taught how many attacks work, always with their defences and under the principle that security capability is neutral and its use is defined by authorisation and conduct. A professional engagement makes that principle concrete: it is authorised and scoped, thorough in its testing, honest in its reporting, verified by retesting, and closed with secure handling of sensitive material, using the understanding of attacks entirely for the client's benefit to find and fix weaknesses before a real attacker does. So the engagement embodies the governing idea, understanding attacks to defend, under authorisation and for the owner's benefit, which is the whole of ethical hacking and where the book concludes.

Contents This chapter on its own page

munotes.in578

The rest of this subject

These notes are cut from the University's printed syllabus. Open the syllabus itself for the same subject.

Issue
Done!