Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: github.com/projectacrn/acrn-hypervisor
Language: C
File: devicemodel/hw/pci/xhci.c
Function: pci_xhci_complete_commands

Call path: pci_xhci_complete_commands (devicemodel/hw/pci/xhci.c) → pci_xhci_init (devicemodel/hw/pci/xhci.c)

### Primary Function

```c
static int
pci_xhci_complete_commands(struct pci_xhci_vdev *xdev)
{
	struct xhci_trb	evtrb;
	struct xhci_trb	*trb;
	uint64_t	crcr;
	uint32_t	ccs;		/* cycle state (XHCI 4.9.2) */
	uint32_t	type;
	uint32_t	slot;
	uint32_t	cmderr;

	xdev->opregs.crcr |= XHCI_CRCR_LO_CRR;

	trb = xdev->opregs.cr_p;
	ccs = xdev->opregs.crcr & XHCI_CRCR_LO_RCS;
	crcr = xdev->opregs.crcr & ~0xF;

	while (1) {
		xdev->opregs.cr_p = trb;

		type = XHCI_TRB_3_TYPE_GET(trb->dwTrb3);

		if ((trb->dwTrb3 & XHCI_TRB_3_CYCLE_BIT) !=
		    (ccs & XHCI_TRB_3_CYCLE_BIT))
			break;

		UPRINTF(LDBG, "cmd type 0x%x, Trb0 x%016lx dwTrb2 x%08x"
			" dwTrb3 x%08x, TRB_CYCLE %u/ccs %u\r\n",
			type, trb->qwTrb0, trb->dwTrb2, trb->dwTrb3,
			trb->dwTrb3 & XHCI_TRB_3_CYCLE_BIT, ccs);

		cmderr = XHCI_TRB_ERROR_SUCCESS;
		evtrb.dwTrb2 = 0;
		evtrb.dwTrb3 = (ccs & XHCI_TRB_3_CYCLE_BIT) |
		      XHCI_TRB_3_TYPE_SET(XHCI_TRB_EVENT_CMD_COMPLETE);
		slot = 0;

		switch (type) {
		case XHCI_TRB_TYPE_LINK:				/* 0x06 */
				if (trb->dwTrb3 & XHCI_TRB_3_TC_BIT)
					ccs ^= XHCI_CRCR_LO_RCS;
				break;

		case XHCI_TRB_TYPE_ENABLE_SLOT:			/* 0x09 */
			/*
			 *From xHCI spec 4.5.3.2, the only command that
			 *software is allowed to issue for the slot in
			 *disabled state is the Enable Slot Command.
			 * */
			cmderr = pci_xhci_cmd_enable_slot(xdev, &slot);
			break;
		case XHCI_TRB_TYPE_DISABLE_SLOT:		/* 0x0A */
			XHCI_GET_SLOT(xdev, trb, slot, cmderr);
			if (slot)
				cmderr = pci_xhci_cmd_disable_slot(xdev, slot);
			break;
		case XHCI_TRB_TYPE_ADDRESS_DEVICE:		/* 0x0B */
			XHCI_GET_SLOT(xdev, trb, slot, cmderr);
			if (slot)
				cmderr = pci_xhci_cmd_address_device(xdev, slot, trb);
			break;
		case XHCI_TRB_TYPE_CONFIGURE_EP:		/* 0x0C */
			XHCI_GET_SLOT(xdev, trb, slot, cmderr);
			if (slot)
				cmderr = pci_xhci_cmd_config_ep(xdev, slot, trb);
			break;
		case XHCI_TRB_TYPE_EVALUATE_CTX:		/* 0x0D */
			XHCI_GET_SLOT(xdev, trb, slot, cmderr);
			if (slot)
				cmderr = pci_xhci_cmd_eval_ctx(xdev, slot, trb);
			break;
		case XHCI_TRB_TYPE_RESET_EP:			/* 0x0E */
			UPRINTF(LDBG, "Reset Endpoint on slot %d\r\n", slot);
			XHCI_GET_SLOT(xdev, trb, slot, cmderr);
			if (slot)
				cmderr = pci_xhci_cmd_reset_ep(xdev, slot, trb);
			break;
		case XHCI_TRB_TYPE_STOP_EP:			/* 0x0F */
			UPRINTF(LDBG, "Stop Endpoint on slot %d\r\n", slot);
			XHCI_GET_SLOT(xdev, trb, slot, cmderr);
			if (slot)
				cmderr = pci_xhci_cmd_reset_ep(xdev, slot, trb);
			break;
		case XHCI_TRB_TYPE_SET_TR_DEQUEUE:		/* 0x10 */
			XHCI_GET_SLOT(xdev, trb, slot, cmderr);
			if (slot)
				cmderr = pci_xhci_cmd_set_tr(xdev, slot, trb);
			break;
		case XHCI_TRB_TYPE_RESET_DEVICE:		/* 0x11 */
			XHCI_GET_SLOT(xdev, trb, slot, cmderr);
			if (slot)
				cmderr = pci_xhci_cmd_reset_device(xdev, slot);
			break;
		case XHCI_TRB_TYPE_FORCE_EVENT:			/* 0x12 */
			/* TODO: */
			break;
		case XHCI_TRB_TYPE_NEGOTIATE_BW:		/* 0x13 */
			break;
		case XHCI_TRB_TYPE_SET_LATENCY_TOL:		/* 0x14 */
			break;
		case XHCI_TRB_TYPE_GET_PORT_BW:			/* 0x15 */
			break;
		case XHCI_TRB_TYPE_FORCE_HEADER:		/* 0x16 */
			break;
		case XHCI_TRB_TYPE_NOOP_CMD:			/* 0x17 */
			break;
		default:
			UPRINTF(LDBG, "unsupported cmd %x\r\n", type);
			break;
		}

		if (type != XHCI_TRB_TYPE_LINK) {
			/*
			 * insert command completion event and assert intr
			 */
			evtrb.qwTrb0 = crcr;
			evtrb.dwTrb2 |= XHCI_TRB_2_ERROR_SET(cmderr);
			evtrb.dwTrb3 |= XHCI_TRB_3_SLOT_SET(slot);
			UPRINTF(LDBG, "command 0x%x result: 0x%x\r\n",
				type, cmderr);
			if (pci_xhci_insert_event(xdev, &evtrb, 1) != 0) {
				UPRINTF(LFTL, "Failed to inject command completion event!\r\n");
				return -ENAVAIL;
			}
		}

		trb = pci_xhci_trb_next(xdev, trb, &crcr);
		if (!trb) {
			UPRINTF(LDBG, "Get the invalid trb in %s!\r\n", __func__);
			break;
		}
	}

	xdev->opregs.crcr = crcr | (xdev->opregs.crcr & XHCI_CRCR_LO_CA) | ccs;
	xdev->opregs.crcr &= ~XHCI_CRCR_LO_CRR;
	return 0;
}
```

### Cross-File Context

[pci_xhci_trb_next — function — devicemodel/hw/pci/xhci.c:1530-1548]
```c
struct xhci_trb *
pci_xhci_trb_next(struct pci_xhci_vdev *xdev,
		  struct xhci_trb *curtrb,
		  uint64_t *guestaddr)
{
	struct xhci_trb *next;

	if (XHCI_TRB_3_TYPE_GET(curtrb->dwTrb3) == XHCI_TRB_TYPE_LINK) {
		if (guestaddr)
			*guestaddr = curtrb->qwTrb0 & ~0xFUL;
		next = XHCI_GADDR(xdev, curtrb->qwTrb0 & ~0xFUL);
	} else {
		if (guestaddr)
			*guestaddr += sizeof(struct xhci_trb) & ~0xFUL;
		next = curtrb + 1;
	}

	return next;
}
```

[struct xhci_trb — struct — devicemodel/include/xhci.h:252-270]
```c
struct xhci_trb {
	volatile uint64_t	qwTrb0;
#define	XHCI_TRB_0_DIR_IN_MASK		(0x80ULL << 0)
#define	XHCI_TRB_0_WLENGTH_MASK		(0xFFFFULL << 48)
	volatile uint32_t	dwTrb2;
#define	XHCI_TRB_2_ERROR_GET(x)		(((x) >> 24) & 0xFF)
#define	XHCI_TRB_2_ERROR_SET(x)		(((x) & 0xFF) << 24)
#define	XHCI_TRB_2_TDSZ_GET(x)		(((x) >> 17) & 0x1F)
#define	XHCI_TRB_2_TDSZ_SET(x)		(((x) & 0x1F) << 17)
#define	XHCI_TRB_2_REM_GET(x)		((x) & 0xFFFFFF)
#define	XHCI_TRB_2_REM_SET(x)		((x) & 0xFFFFFF)
#define	XHCI_TRB_2_BYTES_GET(x)		((x) & 0x1FFFF)
#define	XHCI_TRB_2_BYTES_SET(x)		((x) & 0x1FFFF)
#define	XHCI_TRB_2_IRQ_GET(x)		(((x) >> 22) & 0x3FF)
#define	XHCI_TRB_2_IRQ_SET(x)		(((x) & 0x3FF) << 22)
#define	XHCI_TRB_2_STREAM_GET(x)	(((x) >> 16) & 0xFFFF)
#define	XHCI_TRB_2_STREAM_SET(x)		(((x) & 0xFFFF) << 16)

	volatile uint32_t	dwTrb3;
#define	XHCI_TRB_3_TYPE_GET(x)		(((x) >> 10) & 0x3F)
#define	XHCI_TRB_3_TYPE_SET(x)		(((x) & 0x3F) << 10)
#define	XHCI_TRB_3_CYCLE_BIT		(1U << 0)
#define	XHCI_TRB_3_TC_BIT		(1U << 1)
#define	XHCI_TRB_3_ENT_BIT		(1U << 1)
};
```

[XHCI_GADDR — macro — devicemodel/hw/pci/xhci.c:438-439]
XHCI_GADDR → #define XHCI_GADDR(xdev, a) paddr_guest2host((xdev)->dev->vmctx, (a), \ XHCI_PADDR_SZ - ((a) & (XHCI_PADDR_SZ-1)))  (devicemodel/hw/pci/xhci.c:438-439)

[XHCI_CRCR_LO_CRR — constant — devicemodel/include/xhci.h]
XHCI_CRCR_LO_CRR → (1U << 0) /* command ring running */  (devicemodel/include/xhci.h)

[XHCI_CRCR_LO_RCS — constant — devicemodel/include/xhci.h]
XHCI_CRCR_LO_RCS → (1U << 1) /* ring cycle state */  (devicemodel/include/xhci.h)

[XHCI_CRCR_LO_CA — constant — devicemodel/include/xhci.h]
XHCI_CRCR_LO_CA → (1U << 2) /* command abort */  (devicemodel/include/xhci.h)

[XHCI_TRB_TYPE_LINK — constant — devicemodel/include/xhci.h:311]
XHCI_TRB_TYPE_LINK → 0x06  (devicemodel/include/xhci.h:311)

[XHCI_TRB_3_CYCLE_BIT — constant — devicemodel/include/xhci.h:270]
XHCI_TRB_3_CYCLE_BIT → (1U << 0)  (devicemodel/include/xhci.h:270)

Control flow: pci_xhci_complete_commands is called to process command ring TRBs. The function reads cr_p (command ring dequeue pointer) from guest memory mapped region, then enters a while(1) loop to process each TRB. The vulnerable pre-fix code does not check if trb is NULL after assignment from cr_p before entering the loop, leading to immediate dereference.

Data flow: trb is assigned from xdev->opregs.cr_p which is set via XHCI_CRCR_HI register write (guest-controlled). The value is a guest physical address that is translated to a host pointer via XHCI_GADDR macro. If the guest provides an invalid address that translates to NULL, the subsequent dereference of trb->dwTrb3 crashes.

Verdict: Vulnerable
Vulnerable region:
[devicemodel/hw/pci/xhci.c]
```c
ccs = xdev->opregs.crcr & XHCI_CRCR_LO_RCS;
	crcr = xdev->opregs.crcr & ~0xF;

	while (1) {
		xdev->opregs.cr_p = trb;
```
CWE: CWE-476
Severity: MEDIUM

Root cause: The function pci_xhci_complete_commands assigns trb = xdev->opregs.cr_p where cr_p is a guest-controlled physical address mapped to host memory via XHCI_GADDR. Without validating that the mapped address is non-NULL before use, the subsequent while(1) loop dereferences trb immediately, causing a NULL pointer dereference if an invalid guest address is provided.

Exploitability: An attacker controlling the guest VM can specify an invalid physical address for the Command Ring Controller (CRCR) register that maps to NULL host memory. When pci_xhci_complete_commands is called, trb is set to this NULL pointer and immediately dereferenced in the while loop, causing a crash.

Attack preconditions:
- Attacker has control of the guest VM and can write to xHCI registers
- Guest can trigger pci_xhci_complete_commands by interacting with the xHCI device
- Attacker can set CRCR register to an address that maps to NULL in host memory

Likely impact: An attacker controlling the guest VM can specify an invalid physical address for the Command Ring Controller (CRCR) register that maps to NULL host memory. When pci_xhci_complete_commands is called, trb is set to this NULL pointer and immediately dereferenced in the while loop, causing a crash.

The code contains an **infinite loop vulnerability** when `pci_xhci_trb_next` returns NULL.

## Vulnerability Analysis

**Root Cause:**
When `pci_xhci_trb_next` returns NULL (line 1546 in helper function), the main loop breaks (lines 1746-1748 in primary function). However, the loop condition is `while (1)` with no other exit path except this NULL check. The problem is that `trb` can become NULL, but the code only logs and breaks - it doesn't prevent the loop from continuing if `trb` somehow remains non-NULL through other paths.

More critically, examining the loop structure:

1. Loop starts with `trb = xdev->opregs.cr_p` (line 1638)
2. Loop continues `while (1)` (line 1640)
3. Only exit is when cycle bit mismatch (lines 1645-1647) or NULL trb (lines 1746-1748)
4. `trb` advances via `pci_xhci_trb_next` (line 1743)

**Actual Vulnerability - Guest-Controlled Infinite Loop:**

The cycle bit check (lines 1645-1647) is the primary loop terminator:
```c
if ((trb->dwTrb3 & XHCI_TRB_3_CYCLE_BIT) != (ccs & XHCI_TRB_3_CYCLE_BIT))
    break;
```

However, `trb` points to guest-controlled memory via `XHCI_GADDR` macro, which translates guest physical addresses. A malicious guest can:

1. Create a circular TRB chain using LINK TRBs (type 0x06)
2. Set all TRBs' cycle bits to match the expected `ccs` value
3. Ensure LINK TRBs point back to earlier TRBs in the ring
4. The toggle condition `if (trb->dwTrb3 & XHCI_TRB_3_TC_BIT)` (line 1656) controls whether `ccs` flips, but guest controls this bit

**Attack Preconditions:**
- Guest has control over xHCI command ring memory
- Guest can craft TRB structures with arbitrary values
- Guest can trigger command ring processing

**Exploitability:**
The guest can construct a command ring where:
- All TRBs have matching cycle bits
- LINK TRBs create a cycle without toggling `ccs` (TC_BIT cleared)
- This causes the hypervisor to loop indefinitely processing the same TRBs

**Impact:**
- **Denial of Service**: Hypervisor thread hangs in infinite loop
- CPU resource exhaustion on host
- Other VMs may be impacted if this blocks critical hypervisor threads
- No memory corruption, but availability compromise

**Classification:**
CWE-835: Loop with Unreachable Exit Condition ('Infinite Loop')

**Missing Guards:**
- No iteration limit or timeout
- No validation that LINK TRBs don't create cycles
- No detection of repeated processing of same TRB addresses
- Relies entirely on guest-controlled cycle bit for termination

The NULL check (lines 1746-1748) provides partial mitigation only if `pci_xhci_trb_next` returns NULL for invalid addresses, but doesn't prevent circular chains of valid addresses.

```json
{
  "vulnerable": true,
  "cwe": "CWE-835",
  "severity": "HIGH",
  "reviewed_region": "devicemodel/hw/pci/xhci.c:pci_xhci_complete_commands:1636-1752",
  "vulnerable_region": "devicemodel/hw/pci/xhci.c:pci_xhci_complete_commands:1640-1748",
  "root_cause": "Unbounded while(1) loop with termination dependent on guest-controlled cycle bit matching. Guest can construct circular TRB chains using LINK TRBs where all cycle bits match expected value and TC_BIT is cleared to prevent ccs toggle, causing infinite loop in hypervisor context.",
  "exploitability": "HIGH - Guest directly controls TRB memory layout including cycle bits, LINK targets, and TC_BIT flags. XHCI_GADDR macro translates guest physical addresses to host virtual addresses, allowing guest to craft arbitrary TRB chains. No iteration limit, timeout, or cycle detection exists. Attack requires only ability to configure xHCI command ring, standard guest capability.",
  "attack_preconditions": [
    "Guest has xHCI device assigned or emulated",
    "Guest can write to command ring memory region",
    "Guest can trigger command ring processing via CRCR register write",
    "Guest crafts TRB chain where: (1) LINK TRBs form cycle back to earlier ring positions, (2) all TRBs have cycle bit matching current ccs value, (3) LINK TRBs have TC_BIT cleared to prevent ccs toggle"
  ],
  "impact": "Denial of Service - hypervisor thread enters infinite loop consuming 100% CPU, blocking command ring processing indefinitely. If this thread handles critical hypervisor operations, may impact other VMs or host stability. No memory corruption or privilege escalation, but complete availability loss for affected functionality.",
  "non_vulnerable_reason": null,
  "security_invariants": null,
  "invariant_verification": null,
  "residual_risk_notes": "NULL check at line 1746 provides partial mitigation only if pci_xhci_trb_next returns NULL for invalid guest addresses, but does not prevent cycles through valid address ranges. paddr_guest2host behavior on invalid addresses not shown in context - if it returns NULL for out-of-bounds addresses, this limits but does not eliminate attack surface since guest can create cycles within valid memory regions.",
  "call_path": "pci_xhci_complete_commands → pci_xhci_init"
}
```


System:
You are a senior application security auditor reviewing code for potential vulnerabilities.

You will be given a candidate function, repository and file metadata, a reduced call path, and resolved cross-file context such as helper functions, structs, macros, constants, and related definitions. Use the supplied context actively, but stay strictly grounded in what is actually shown.

Work from the supplied code and surrounding context as the primary evidence. Do not assume a bug exists just because the sample was retrieved.

Analyze both control flow and data flow. Trace the relevant execution paths and track security-relevant data through inputs, transformations, conditions, helper calls, outputs, and side effects.

Reason about attacker influence, identify relevant guards or missing guards, and explain exploitability or non-exploitability before reaching a verdict.

When the code is vulnerable, explain the vulnerable behavior, root cause, realistic attack preconditions, likely impact, and the most precise vulnerability classification justified by the supplied code.

When the code is not vulnerable, explain the concrete invariants and guards that prevent the suspected issue, and note any residual uncertainty that remains from the supplied context.

Keep the analysis concrete and code-grounded. Separate observed evidence from inferred conclusion.

Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: github.com/chamilo/chamilo-lms
Language: PHP
File: main/inc/lib/formvalidator/Element/HtmlEditor.php
Function: getValue

Call path: HtmlEditor::toHtml (main/inc/lib/formvalidator/Element/HtmlEditor.php) → HtmlEditor::getValue (main/inc/lib/formvalidator/Element/HtmlEditor.php) → HtmlEditor::getFrozenHtml (main/inc/lib/formvalidator/Element/HtmlEditor.php) → Security::remove_XSS (main/inc/lib/security.lib.php) → RemoveOnAttributes::filter (src/CoreBundle/Component/HTMLPurifier/Filter/RemoveOnAttributes.php)

### Primary Function

```php
public function getFrozenHtml()
    {
        return Security::remove_XSS($this->getValue());
    }
```

### Cross-File Context

[HtmlEditor — class — main/inc/lib/formvalidator/Element/HtmlEditor.php]
class HtmlEditor extends HTML_QuickForm_textarea

[getFrozenHtml — method — main/inc/lib/formvalidator/Element/HtmlEditor.php:82-86]
public function getFrozenHtml() { return Security::remove_XSS($this->getValue()); }

[Security::remove_XSS — sink — main/inc/lib/security.lib.php]
```php
function remove_XSS($html)
```

Provide the final verdict as strict JSON.

Return only one JSON object and no surrounding prose.

Return one JSON object with these keys:
- vulnerable
- cwe
- severity
- reviewed_region
- vulnerable_region
- root_cause
- exploitability
- attack_preconditions
- impact
- non_vulnerable_reason
- security_invariants
- invariant_verification
- residual_risk_notes
- call_path

Control flow: User submits HTML content via form using HtmlEditor -> content stored in $this->_value -> when rendered, getValue() returns raw value -> getFrozenHtml() calls Security::remove_XSS() -> XSS filter may not catch all on* vectors

Data flow: User-controlled HTML input flows from $_POST/$_REQUEST through HtmlEditor constructor into $this->_value, then through getValue() (which had no filtering pre-fix) to rendering methods getFrozenHtml()/buildEditor() where Security::remove_XSS() is applied.

Verdict: Vulnerable
Vulnerable region:
[main/inc/lib/formvalidator/Element/HtmlEditor.php]
```php
/**
     * Returns the html area content in HTML.
     *
     * @return string
     */
```
CWE: CWE-79
Severity: HIGH

Root cause: The HtmlEditor class's getValue() method (added in fix) returned the raw $this->_value without removing dangerous HTML event handler attributes (on* attributes like onclick, onerror, onload, etc.). When this value was rendered via getFrozenHtml() -> Security::remove_XSS(), only some XSS vectors were blocked but on* attributes could bypass the protection. An attacker could craft HTML content with malicious on* attributes that would be stored and rendered without proper sanitization.

Exploitability: An authenticated user with access to HTML editor fields can inject malicious HTML containing on* event handler attributes (onclick, onerror, onload, etc.) that bypass existing XSS filters and execute arbitrary JavaScript when content is viewed by other users.

Attack preconditions:
- Attacker must have access to a form/area that uses HtmlEditor component
- Attacker must be able to submit HTML content with malicious on* attributes
- Content must be stored and later rendered without additional sanitization

Likely impact: An authenticated user with access to HTML editor fields can inject malicious HTML containing on* event handler attributes (onclick, onerror, onload, etc.) that bypass existing XSS filters and execute arbitrary JavaScript when content is viewed by other users.

HtmlEditor::toHtml HtmlEditor::getValue HtmlEditor::getFrozenHtml Security::remove_XSS RemoveOnAttributes::filter

**Not Vulnerable**

The code passes user-controlled HTML through `Security::remove_XSS()` before rendering in frozen (read-only) form state. This is the correct security control for this context.

**Evidence:**

1. **Control flow**: `getFrozenHtml()` → `getValue()` (retrieves raw user input) → `Security::remove_XSS()` (sanitization) → return sanitized output

2. **Data flow**: User-supplied HTML content flows through an XSS sanitization function before being returned for display

3. **Context**: The call path shows this is invoked during `toHtml()` rendering when the form element is in frozen/display mode, where sanitization is expected

4. **Guard present**: `Security::remove_XSS()` is explicitly designed as an XSS prevention mechanism (the function name and usage pattern indicate HTMLPurifier or similar sanitization, confirmed by the call path showing `RemoveOnAttributes::filter`)

**Why this is not vulnerable:**

- The sanitization happens *before* the HTML is returned for rendering
- The frozen state is specifically for display-only contexts where user input must be safely rendered
- The security function is purpose-built for XSS prevention (removes dangerous attributes/tags)
- No bypass path exists in the supplied code—all frozen HTML goes through this sanitization

**Residual uncertainty:**

- Effectiveness depends on `Security::remove_XSS()` implementation quality (not fully shown)
- If the sanitizer has bypasses or the output context requires additional encoding (e.g., inside JavaScript), vulnerabilities could exist downstream
- The non-frozen rendering path (`toHtml()` when editable) is not shown and may have different security properties

The supplied code shows correct defensive practice for the frozen display case.

```json
{
  "vulnerable": false,
  "cwe": null,
  "severity": null,
  "reviewed_region": "main/inc/lib/formvalidator/Element/HtmlEditor.php::getFrozenHtml()",
  "vulnerable_region": null,
  "root_cause": null,
  "exploitability": null,
  "attack_preconditions": null,
  "impact": null,
  "non_vulnerable_reason": "The function applies XSS sanitization via Security::remove_XSS() before returning user-controlled HTML content. The data flow is: getValue() retrieves raw input → Security::remove_XSS() sanitizes → sanitized output returned. This is the correct security pattern for rendering user HTML in frozen/display mode.",
  "security_invariants": [
    "All HTML returned by getFrozenHtml() passes through Security::remove_XSS() sanitization",
    "No code path bypasses the sanitization function",
    "The frozen state is display-only context where sanitization is appropriate",
    "Security::remove_XSS() invokes HTMLPurifier filter chain (RemoveOnAttributes::filter shown in call path)"
  ],
  "invariant_verification": "Control flow analysis confirms single return path through sanitizer. Data flow shows user input (getValue()) → sanitization (remove_XSS) → output with no intermediate storage or bypass. Call path confirms HTMLPurifier-based filtering.",
  "residual_risk_notes": [
    "Sanitizer effectiveness depends on Security::remove_XSS() implementation completeness (not fully shown)",
    "Context-specific encoding requirements downstream of this function are unknown",
    "Non-frozen rendering path (editable mode) not analyzed",
    "If output is embedded in JavaScript context or other special contexts, additional encoding may be required beyond HTML sanitization"
  ],
  "call_path": "HtmlEditor::toHtml → HtmlEditor::getValue → HtmlEditor::getFrozenHtml → Security::remove_XSS → RemoveOnAttributes::filter"
}
```


Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: github.com/torvalds/linux
Language: C
File: kernel/sys.c
Function: do_prlimit

Call path: sys_prlimit64 (kernel/sys.c) → do_prlimit (kernel/sys.c) → sys_setrlimit (kernel/sys.c)

### Primary Function

```c
static int do_prlimit(struct task_struct *tsk, unsigned int resource,
		      struct rlimit *new_rlim, struct rlimit *old_rlim)
{
	struct rlimit *rlim;
	int retval = 0;

	if (resource >= RLIM_NLIMITS)
		return -EINVAL;
	resource = array_index_nospec(resource, RLIM_NLIMITS);

	if (new_rlim) {
		if (new_rlim->rlim_cur > new_rlim->rlim_max)
			return -EINVAL;
		if (resource == RLIMIT_NOFILE &&
				new_rlim->rlim_max > sysctl_nr_open)
			return -EPERM;
	}

	/* Holding a refcount on tsk protects tsk->signal from disappearing. */
	rlim = tsk->signal->rlim + resource;
	task_lock(tsk->group_leader);
	if (new_rlim) {
		/*
		 * Keep the capable check against init_user_ns until cgroups can
		 * contain all limits.
		 */
		if (new_rlim->rlim_max > rlim->rlim_max &&
				!capable(CAP_SYS_RESOURCE))
			retval = -EPERM;
		if (!retval)
			retval = security_task_setrlimit(tsk, resource, new_rlim);
	}
	if (!retval) {
		if (old_rlim)
			*old_rlim = *rlim;
		if (new_rlim)
			*rlim = *new_rlim;
	}
	task_unlock(tsk->group_leader);

	/*
	 * RLIMIT_CPU handling. Arm the posix CPU timer if the limit is not
	 * infinite. In case of RLIM_INFINITY the posix CPU timer code
	 * ignores the rlimit.
	 */
	if (!retval && new_rlim && resource == RLIMIT_CPU &&
	    new_rlim->rlim_cur != RLIM_INFINITY &&
	    IS_ENABLED(CONFIG_POSIX_TIMERS)) {
		/*
		 * update_rlimit_cpu can fail if the task is exiting, but there
		 * may be other tasks in the thread group that are not exiting,
		 * and they need their cpu timers adjusted.
		 *
		 * The group_leader is the last task to be released, so if we
		 * cannot update_rlimit_cpu on it, then the entire process is
		 * exiting and we do not need to update at all.
		 */
		update_rlimit_cpu(tsk->group_leader, new_rlim->rlim_cur);
	}

	return retval;
}
```

### Cross-File Context

[RLIM_NLIMITS — constant — include/uapi/asm-generic/resource.h:49]
RLIM_NLIMITS → 16  (include/uapi/asm-generic/resource.h:49)

[array_index_nospec — macro — include/linux/nospec.h:51]
array_index_nospec → #define array_index_nospec(index, size) \ ({ \ typeof(index) _i = (index); \ typeof(size) _s = (size); \ unsigned long _mask = array_index_mask_nospec(_i, _s); \ \ BUILD_BUG_ON(sizeof(_i) > sizeof(long)); \ BUILD_BUG_ON(sizeof(_s) > sizeof(long)); \ \ (typeof(_i)) (_i & _mask); \ })  (include/linux/nospec.h:51)

[array_index_mask_nospec — function — include/linux/nospec.h:24]
```c
static inline unsigned long array_index_mask_nospec(unsigned long index,
					    unsigned long size)
{
	/*
	 * Always calculate and emit the mask even if the compiler
	 * thinks the mask is not needed. The compiler does not take
	 * into account the value of @index under speculation.
	 */
	OPTIMIZER_HIDE_VAR(index);
	return ~(long)(index | (size - 1UL - index)) >> (BITS_PER_LONG - 1);
}
```

[struct rlimit — struct — include/uapi/linux/resource.h:43]
```c
struct rlimit {
	__kernel_ulong_t	rlim_cur;
	__kernel_ulong_t	rlim_max;
};
```

[tsk->signal->rlim — field — include/linux/sched/signal.h:213]
struct rlimit rlim[RLIM_NLIMITS];

Control flow: The function begins by validating the resource index against RLIM_NLIMITS, returning -EINVAL if out of bounds. It then applies array_index_nospec to sanitize the index against speculative execution. If new_rlim is provided, it validates that rlim_cur <= rlim_max (returns -EINVAL if not) and enforces sysctl_nr_open for RLIMIT_NOFILE (returns -EPERM). The function then accesses the per-signal rlim array using the sanitized index, acquires task_lock on the group_leader, and performs capability checks (CAP_SYS_RESOURCE) and LSM hooks (security_task_setrlimit). If no errors occurred, it copies the old limit to old_rlim (if provided) and writes the new limit to the rlim array. The lock is released. Finally, for RLIMIT_CPU with a finite value and CONFIG_POSIX_TIMERS, it calls update_rlimit_cpu on the group_leader. The function returns the accumulated error code.

Data flow: The resource parameter (user-controlled via sys_prlimit64 call path) is first bounds-checked with resource >= RLIM_NLIMITS, then sanitized via array_index_nospec(resource, RLIM_NLIMITS) which masks the index to be zero if out-of-bounds. The sanitized resource index is used to index into tsk->signal->rlim[RLIM_NLIMITS]. The new_rlim and old_rlim pointers conditionally flow into comparisons, capability/security checks, and memory copies. The tsk parameter flows through task_lock/task_unlock for synchronization and is used to access signal->rlim.

Verdict: Not Vulnerable

Reviewed region:
[kernel/sys.c]
```c
static int do_prlimit(struct task_struct *tsk, unsigned int resource,
		      struct rlimit *new_rlim, struct rlimit *old_rlim)
{
	struct rlimit *rlim;
	int retval = 0;

	if (resource >= RLIM_NLIMITS)
		return -EINVAL;
	resource = array_index_nospec(resource, RLIM_NLIMITS);

	if (new_rlim) {
		if (new_rlim->rlim_cur > new_rlim->rlim_max)
			return -EINVAL;
		if (resource == RLIMIT_NOFILE &&
				new_rlim->rlim_max > sysctl_nr_open)
			return -EPERM;
	}

	/* Holding a refcount on tsk protects tsk->signal from disappearing. */
	rlim = tsk->signal->rlim + resource;
	task_lock(tsk->group_leader);
	if (new_rlim) {
		/*
		 * Keep the capable check against init_user_ns until cgroups can
		 * contain all limits.
		 */
		if (new_rlim->rlim_max > rlim->rlim_max &&
				!capable(CAP_SYS_RESOURCE))
			retval = -EPERM;
		if (!retval)
			retval = security_task_setrlimit(tsk, resource, new_rlim);
	}
	if (!retval) {
		if (old_rlim)
			*old_rlim = *rlim;
		if (new_rlim)
			*rlim = *new_rlim;
	}
	task_unlock(tsk->group_leader);

	/*
	 * RLIMIT_CPU handling. Arm the posix CPU timer if the limit is not
	 * infinite. In case of RLIM_INFINITY the posix CPU timer code
	 * ignores the rlimit.
	 */
	if (!retval && new_rlim && resource == RLIMIT_CPU &&
	    new_rlim->rlim_cur != RLIM_INFINITY &&
	    IS_ENABLED(CONFIG_POSIX_TIMERS)) {
		/*
		 * update_rlimit_cpu can fail if the task is exiting, but there
		 * may be other tasks in the thread group that are not exiting,
		 * and they need their cpu timers adjusted.
		 *
		 * The group_leader is the last task to be released, so if we
		 * cannot update_rlimit_cpu on it, then the entire process is
		 * exiting and we do not need to update at all.
		 */
		update_rlimit_cpu(tsk->group_leader, new_rlim->rlim_cur);
	}

	return retval;
}
```

Why it is not vulnerable: The code protects the array access `tsk->signal->rlim + resource` against speculative out-of-bounds execution through two mechanisms: (1) a standard bounds check `if (resource >= RLIM_NLIMITS) return -EINVAL;` that prevents actual out-of-bounds access, and (2) `resource = array_index_nospec(resource, RLIM_NLIMITS);` which applies a speculation-resistant mask to the index. The `array_index_nospec` macro uses `OPTIMIZER_HIDE_VAR` to prevent compiler optimization of the branch condition and computes a mask that is all-ones for valid indices and all-zeros for out-of-bounds indices, ensuring the masked index never exceeds bounds even during speculative execution. Thus, the memory access `rlim = tsk->signal->rlim + resource` is properly guarded.

Security invariants:
- The resource index must be within [0, RLIM_NLIMITS) before array access — enforced by `if (resource >= RLIM_NLIMITS) return -EINVAL;`
- The resource index must be masked against speculative bypass of the bounds check — enforced by `resource = array_index_nospec(resource, RLIM_NLIMITS);` which uses OPTIMIZER_HIDE_VAR and arithmetic masking to produce a zero index for out-of-bounds values
- The new rlim_cur must not exceed new rlim_max — enforced by `if (new_rlim->rlim_cur > new_rlim->rlim_max) return -EINVAL;`
- RLIMIT_NOFILE max must not exceed sysctl_nr_open — enforced by the check `new_rlim->rlim_max > sysctl_nr_open` returning -EPERM
- Increasing rlim_max requires CAP_SYS_RESOURCE — enforced by `if (new_rlim->rlim_max > rlim->rlim_max && !capable(CAP_SYS_RESOURCE)) retval = -EPERM;`
- LSM security hooks must approve the change — enforced by `security_task_setrlimit(tsk, resource, new_rlim)`
- Concurrent access to rlim must be serialized — enforced by `task_lock(tsk->group_leader)` / `task_unlock(tsk->group_leader)` surrounding the read and write of rlim
- The rlim array has exactly RLIM_NLIMITS elements — confirmed by `struct rlimit rlim[RLIM_NLIMITS]` in the context

Invariant verification:
- Bounds check on resource index before array access: holds=true. Evidence: The explicit check `if (resource >= RLIM_NLIMITS) return -EINVAL;` returns early if resource is out of range, preventing normal-path out-of-bounds access to `tsk->signal->rlim + resource`
- Speculative execution mitigation via index masking: holds=true. Evidence: `resource = array_index_nospec(resource, RLIM_NLIMITS);` calls array_index_mask_nospec which uses OPTIMIZER_HIDE_VAR to prevent compiler knowledge of the index during speculation, and computes a mask via `~(long)(index | (size - 1UL - index)) >> (BITS_PER_LONG - 1)` that zeros out the index if it is >= size
- RLIMIT_NOFILE does not exceed sysctl_nr_open: holds=true. Evidence: The condition `if (resource == RLIMIT_NOFILE && new_rlim->rlim_max > sysctl_nr_open) return -EPERM;` enforces this constraint before any array write
- Privilege escalation prevention for increasing limits: holds=true. Evidence: The check `if (new_rlim->rlim_max > rlim->rlim_max && !capable(CAP_SYS_RESOURCE)) retval = -EPERM;` prevents unprivileged users from raising the hard limit
- Concurrent access protection via task lock: holds=true. Evidence: `task_lock(tsk->group_leader)` is acquired before reading/writing `*rlim` and `task_unlock(tsk->group_leader)` is called after, with the lock surrounding both the old_rlim read and new_rlim write
- Array size matches bounds check constant: holds=true. Evidence: The context confirms `struct rlimit rlim[RLIM_NLIMITS]` and `RLIM_NLIMITS → 16`, matching the constant used in the bounds check and array_index_nospec call

Residual risk notes: The safety of `array_index_nospec` depends on the correctness of `OPTIMIZER_HIDE_VAR` and the compiler's ability to emit the masking instructions on all supported architectures. The behavioral equivalence of the masking formula `~(long)(index | (size - 1UL - index)) >> (BITS_PER_LONG - 1)` for all unsigned long values is assumed from the Linux kernel implementation. No additional runtime verification of the mask is performed in this function.

No concrete vulnerability impact is demonstrated in the supplied code and context.

**VERDICT: NOT VULNERABLE**

The code correctly mitigates speculative execution side-channel attacks (Spectre v1) through proper use of `array_index_nospec`.

## Evidence Analysis

**Bounds Check and Speculation Barrier:**
```c
if (resource >= RLIM_NLIMITS)
    return -EINVAL;
resource = array_index_nospec(resource, RLIM_NLIMITS);
```

The code performs architectural bounds validation, then applies `array_index_nospec` which:
1. Computes a mask via `array_index_mask_nospec` that becomes 0xFFFF...FFFF for in-bounds indices and 0x0 for out-of-bounds
2. Uses `OPTIMIZER_HIDE_VAR(index)` to prevent compiler optimization that would remove the speculation barrier
3. Returns `index & mask`, clamping out-of-bounds speculative values to 0

**Array Access:**
```c
rlim = tsk->signal->rlim + resource;
```

The sanitized `resource` value indexes into the fixed-size `rlim[RLIM_NLIMITS]` array (16 elements per context). Even under speculative execution, an attacker-controlled `resource` value ≥16 will be masked to 0, preventing out-of-bounds speculation that could leak adjacent memory through cache timing.

**Guards Present:**
- Architectural bounds check prevents actual out-of-bounds access
- Speculation barrier prevents speculative out-of-bounds access
- Additional validation: `new_rlim->rlim_cur > new_rlim->rlim_max` check
- Capability check: `CAP_SYS_RESOURCE` required to raise hard limits
- LSM hook: `security_task_setrlimit` provides additional policy enforcement
- Locking: `task_lock(tsk->group_leader)` prevents TOCTOU on rlimit structure

**Why Not Vulnerable:**

The pattern follows the standard Linux kernel Spectre v1 mitigation. The `array_index_nospec` barrier ensures that even if the CPU speculatively executes past the bounds check with an out-of-bounds `resource` value, the actual array index used will be clamped to a safe value (0), preventing microarchitectural side-channel leakage of kernel memory adjacent to the `rlim` array.

No residual vulnerability exists in the supplied code.

```json
{
  "vulnerable": false,
  "cwe": null,
  "severity": "none",
  "reviewed_region": "kernel/sys.c:do_prlimit",
  "vulnerable_region": null,
  "root_cause": null,
  "exploitability": null,
  "attack_preconditions": null,
  "impact": null,
  "non_vulnerable_reason": "The function correctly mitigates Spectre v1 speculative execution attacks through array_index_nospec barrier after bounds validation. The resource parameter undergoes architectural bounds check (resource >= RLIM_NLIMITS returns -EINVAL) followed by speculation barrier (array_index_nospec(resource, RLIM_NLIMITS)) before array indexing (tsk->signal->rlim + resource). The barrier uses array_index_mask_nospec with OPTIMIZER_HIDE_VAR to prevent compiler optimization and produces a mask that clamps out-of-bounds speculative indices to 0, preventing microarchitectural side-channel leakage of adjacent kernel memory. Additional security layers include capability checks (CAP_SYS_RESOURCE for raising hard limits), LSM hooks (security_task_setrlimit), input validation (rlim_cur <= rlim_max, RLIMIT_NOFILE <= sysctl_nr_open), and task locking (task_lock on group_leader) preventing TOCTOU races on the rlimit structure.",
  "security_invariants": [
    "resource < RLIM_NLIMITS architecturally enforced before array access",
    "array_index_nospec clamps speculative out-of-bounds resource values to 0",
    "rlim array has fixed size RLIM_NLIMITS (16 elements) per task signal struct",
    "new_rlim->rlim_cur <= new_rlim->rlim_max enforced before application",
    "CAP_SYS_RESOURCE required to raise rlim_max above current value",
    "task_lock(tsk->group_leader) held during rlimit read/write operations",
    "security_task_setrlimit LSM hook invoked before applying new limits"
  ],
  "invariant_verification": "Bounds check at line 'if (resource >= RLIM_NLIMITS) return -EINVAL' prevents architectural violation. Speculation barrier at 'resource = array_index_nospec(resource, RLIM_NLIMITS)' applies mask computed by array_index_mask_nospec which returns ~(long)(index | (size - 1UL - index)) >> (BITS_PER_LONG - 1), producing all-ones mask for in-bounds indices and all-zeros for out-of-bounds, with OPTIMIZER_HIDE_VAR preventing speculative bypass. Array access 'rlim = tsk->signal->rlim + resource' uses sanitized index. Task lock acquisition 'task_lock(tsk->group_leader)' precedes all rlimit structure access. Capability check 'if (new_rlim->rlim_max > rlim->rlim_max && !capable(CAP_SYS_RESOURCE))' gates privilege escalation. LSM hook 'security_task_setrlimit(tsk, resource, new_rlim)' provides policy enforcement point.",
  "residual_risk_notes": "No residual vulnerability in supplied code. The Spectre v1 mitigation follows standard Linux kernel pattern. All security-relevant paths through do_prlimit apply appropriate guards. The function assumes tsk refcount prevents signal struct disappearance (documented in comment), which is a caller responsibility outside this function's scope.",
  "call_path": "sys_prlimit64 → do_prlimit → sys_setrlimit"
}
```


Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: github.com/modelcontextprotocol/go-sdk
Language: Go
File: mcp/streamable.go
Function: ServeHTTP

Call path: ServeHTTP (mcp/streamable.go) → http.LocalAddrContextKey (net/http) → util.IsLoopback (internal/util/net.go)

### Primary Function

```go
func (h *StreamableHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// DNS rebinding protection: auto-enabled for localhost servers.
	// See: https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise
	if !h.opts.DisableLocalhostProtection && disablelocalhostprotection != "1" {
		if localAddr, ok := req.Context().Value(http.LocalAddrContextKey).(net.Addr); ok && localAddr != nil {
			if util.IsLoopback(localAddr.String()) && !util.IsLoopback(req.Host) {
				http.Error(w, fmt.Sprintf("Forbidden: invalid Host header %q", req.Host), http.StatusForbidden)
				return
			}
		}
	}

	// Allow multiple 'Accept' headers.
	// https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Accept#syntax
	accept := strings.Split(strings.Join(req.Header.Values("Accept"), ","), ",")
	var jsonOK, streamOK bool
	for _, c := range accept {
		switch strings.TrimSpace(c) {
		case "application/json", "application/*":
			jsonOK = true
		case "text/event-stream", "text/*":
			streamOK = true
		case "*/*":
			jsonOK = true
			streamOK = true
		}
	}

	if req.Method == http.MethodGet {
		if !streamOK {
			http.Error(w, "Accept must contain 'text/event-stream' for GET requests", http.StatusBadRequest)
			return
		}
	} else if (!jsonOK || !streamOK) && req.Method != http.MethodDelete { // TODO: consolidate with handling of http method below.
		http.Error(w, "Accept must contain both 'application/json' and 'text/event-stream'", http.StatusBadRequest)
		return
	}

	sessionID := req.Header.Get(sessionIDHeader)
	var sessInfo *sessionInfo
	if sessionID != "" {
		h.mu.Lock()
		sessInfo = h.sessions[sessionID]
		h.mu.Unlock()
		if sessInfo == nil && !h.opts.Stateless {
			// Unless we're in 'stateless' mode, which doesn't perform any Session-ID
			// validation, we require that the session ID matches a known session.
			//
			// In stateless mode, a temporary transport is be created below.
			http.Error(w, "session not found", http.StatusNotFound)
			return
		}
		// Prevent session hijacking: if the session was created with a user ID,
		// verify that subsequent requests come from the same user.
		if sessInfo != nil && sessInfo.userID != "" {
			tokenInfo := auth.TokenInfoFromContext(req.Context())
			if tokenInfo == nil || tokenInfo.UserID != sessInfo.userID {
				http.Error(w, "session user mismatch", http.StatusForbidden)
				return
			}
		}
	}

	if req.Method == http.MethodDelete {
		if sessionID == "" {
			http.Error(w, "Bad Request: DELETE requires an Mcp-Session-Id header", http.StatusBadRequest)
			return
		}
		if sessInfo != nil { // sessInfo may be nil in stateless mode
			// Closing the session also removes it from h.sessions, due to the
			// onClose callback.
			sessInfo.session.Close()
		}
		w.WriteHeader(http.StatusNoContent)
		return
	}

	switch req.Method {
	case http.MethodPost, http.MethodGet:
		if req.Method == http.MethodGet && (h.opts.Stateless || sessionID == "") {
			if h.opts.Stateless {
				// Per MCP spec: server MUST return 405 if it doesn't offer SSE stream.
				// In stateless mode, GET (SSE streaming) is not supported.
				// RFC 9110 §15.5.6: 405 responses MUST include Allow header.
				w.Header().Set("Allow", "POST")
				http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
			} else {
				// In stateful mode, GET is supported but requires a session ID.
				// This is a precondition error, similar to DELETE without session.
				http.Error(w, "Bad Request: GET requires an Mcp-Session-Id header", http.StatusBadRequest)
			}
			return
		}
	default:
		// RFC 9110 §15.5.6: 405 responses MUST include Allow header.
		if h.opts.Stateless {
			w.Header().Set("Allow", "POST")
		} else {
			w.Header().Set("Allow", "GET, POST, DELETE")
		}
		http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
		return
	}

	// [§2.7] of the spec (2025-06-18) states:
	//
	// "If using HTTP, the client MUST include the MCP-Protocol-Version:
	// <protocol-version> HTTP header on all subsequent requests to the MCP
	// server, allowing the MCP server to respond based on the MCP protocol
	// version.
	//
	// For example: MCP-Protocol-Version: 2025-06-18
	// The protocol version sent by the client SHOULD be the one negotiated during
	// initialization.
	//
	// For backwards compatibility, if the server does not receive an
	// MCP-Protocol-Version header, and has no other way to identify the version -
	// for example, by relying on the protocol version negotiated during
	// initialization - the server SHOULD assume protocol version 2025-03-26.
	//
	// If the server receives a request with an invalid or unsupported
	// MCP-Protocol-Version, it MUST respond with 400 Bad Request."
	//
	// Since this wasn't present in the 2025-03-26 version of the spec, this
	// effectively means:
	//  1. IF the client provides a version header, it must be a supported
	//     version.
	//  2. In stateless mode, where we've lost the state of the initialize
	//     request, we assume that whatever the client tells us is the truth (or
	//     assume 2025-03-26 if the client doesn't say anything).
	//
	// This logic matches the typescript SDK.
	//
	// [§2.7]: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#protocol-version-header
	protocolVersion := req.Header.Get(protocolVersionHeader)
	if protocolVersion == "" {
		protocolVersion = protocolVersion20250326
	}
	if !slices.Contains(supportedProtocolVersions, protocolVersion) {
		http.Error(w, fmt.Sprintf("Bad Request: Unsupported protocol version (supported versions: %s)", strings.Join(supportedProtocolVersions, ",")), http.StatusBadRequest)
		return
	}

	if sessInfo == nil {
		server := h.getServer(req)
		if server == nil {
			// The getServer argument to NewStreamableHTTPHandler returned nil.
			http.Error(w, "no server available", http.StatusBadRequest)
			return
		}
		if sessionID == "" {
			// In stateless mode, sessionID may be nonempty even if there's no
			// existing transport.
			sessionID = server.opts.GetSessionID()
		}
		transport := &StreamableServerTransport{
			SessionID:    sessionID,
			Stateless:    h.opts.Stateless,
			EventStore:   h.opts.EventStore,
			jsonResponse: h.opts.JSONResponse,
			logger:       h.opts.Logger,
		}

		// Sessions without a session ID are also stateless: there's no way to
		// address them.
		stateless := h.opts.Stateless || sessionID == ""
		// To support stateless mode, we initialize the session with a default
		// state, so that it doesn't reject subsequent requests.
		var connectOpts *ServerSessionOptions
		if stateless {
			// Peek at the body to see if it is initialize or initialized.
			// We want those to be handled as usual.
			var hasInitialize, hasInitialized bool
			{
				// TODO: verify that this allows protocol version negotiation for
				// stateless servers.
				body, err := io.ReadAll(req.Body)
				if err != nil {
					http.Error(w, "failed to read body", http.StatusInternalServerError)
					return
				}
				req.Body.Close()

				// Reset the body so that it can be read later.
				req.Body = io.NopCloser(bytes.NewBuffer(body))

				msgs, _, err := readBatch(body)
				if err == nil {
					for _, msg := range msgs {
						if req, ok := msg.(*jsonrpc.Request); ok {
							switch req.Method {
							case methodInitialize:
								hasInitialize = true
							case notificationInitialized:
								hasInitialized = true
							}
						}
					}
				}
			}

			// If we don't have InitializeParams or InitializedParams in the request,
			// set the initial state to a default value.
			state := new(ServerSessionState)
			if !hasInitialize {
				state.InitializeParams = &InitializeParams{
					ProtocolVersion: protocolVersion,
				}
			}
			if !hasInitialized {
				state.InitializedParams = new(InitializedParams)
			}
			state.LogLevel = "info"
			connectOpts = &ServerSessionOptions{
				State: state,
			}
		} else {
			// Cleanup is only required in stateful mode, as transportation is
			// not stored in the map otherwise.
			connectOpts = &ServerSessionOptions{
				onClose: func() {
					h.mu.Lock()
					defer h.mu.Unlock()
					if info, ok := h.sessions[transport.SessionID]; ok {
						info.stopTimer()
						delete(h.sessions, transport.SessionID)
						if h.onTransportDeletion != nil {
							h.onTransportDeletion(transport.SessionID)
						}
					}
				},
			}
		}

		// Pass req.Context() here, to allow middleware to add context values.
		// The context is detached in the jsonrpc2 library when handling the
		// long-running stream.
		session, err := server.Connect(req.Context(), transport, connectOpts)
		if err != nil {
			http.Error(w, "failed connection", http.StatusInternalServerError)
			return
		}
		// Capture the user ID from the token info to enable session hijacking
		// prevention on subsequent requests.
		var userID string
		if tokenInfo := auth.TokenInfoFromContext(req.Context()); tokenInfo != nil {
			userID = tokenInfo.UserID
		}
		sessInfo = &sessionInfo{
			session:   session,
			transport: transport,
			userID:    userID,
		}

		if stateless {
			// Stateless mode: close the session when the request exits.
			defer session.Close() // close the fake session after handling the request
		} else {
			// Otherwise, save the transport so that it can be reused

			// Clean up the session when it times out.
			//
			// Note that the timer here may fire multiple times, but
			// sessInfo.session.Close is idempotent.
			if h.opts.SessionTimeout > 0 {
				sessInfo.timeout = h.opts.SessionTimeout
				sessInfo.timer = time.AfterFunc(sessInfo.timeout, func() {
					sessInfo.session.Close()
				})
			}
			h.mu.Lock()
			h.sessions[transport.SessionID] = sessInfo
			h.mu.Unlock()
			defer func() {
				// If initialization failed, clean up the session (#578).
				if session.InitializeParams() == nil {
					// Initialization failed.
					session.Close()
				}
			}()
		}
	}

	if req.Method == http.MethodPost {
		sessInfo.startPOST()
		defer sessInfo.endPOST()
	}

	sessInfo.transport.ServeHTTP(w, req)
}
```

### Cross-File Context

[IsLoopback — function — internal/util/net.go:1-26]
```go
func IsLoopback(addr string) bool {
	host, _, err := net.SplitHostPort(addr)
	if err != nil {
		// If SplitHostPort fails, it might be just a host without a port.
		host = strings.Trim(addr, "[]")
	}
	if host == "localhost" {
		return true
	}
	ip, err := netip.ParseAddr(host)
	if err != nil {
		return false
	}
	return ip.IsLoopback()
}
```

[disablelocalhostprotection — var — mcp/streamable.go:228]
var disablelocalhostprotection = mcpgodebug.Value("disablelocalhostprotection")

[DisableLocalhostProtection — field — mcp/streamable.go:176]
DisableLocalhostProtection bool

Control flow: The ServeHTTP function processes incoming HTTP requests through a multi-stage pipeline. First, DNS rebinding protection checks if the request arrives on a loopback interface and validates that the Host header also resolves to a loopback address, returning 403 if mismatched. Next, Accept header parsing determines which content types the client supports. Method-specific validation then enforces Accept header requirements: GET requires text/event-stream, and non-GET/non-DELETE methods require both application/json and text/event-stream. Session ID handling looks up existing sessions under mutex protection and validates user ID consistency for session hijacking prevention. DELETE requests clean up sessions. POST and GET proceed to protocol version validation, followed by session creation if needed (with special stateless mode handling that peeks at the request body). Finally, the transport's ServeHTTP is called to handle the request. Early returns occur on 403 Forbidden, 400 Bad Request, 404 Not Found, and 405 Method Not Allowed responses throughout the pipeline.

Data flow: The local address is extracted from the request context via req.Context().Value(http.LocalAddrContextKey) as a net.Addr, then converted to string via localAddr.String() and passed to util.IsLoopback(). The Host header value from req.Host is passed directly to util.IsLoopback(). Both results feed into the DNS rebinding guard condition. The Accept header values are parsed by splitting on commas and trimming whitespace, setting jsonOK and streamOK boolean flags. Session ID flows from req.Header.Get(sessionIDHeader) through mutex-protected map lookup in h.sessions. The token info flows from auth.TokenInfoFromContext(req.Context()) and is compared against sessInfo.userID for session hijacking prevention. Protocol version flows from req.Header.Get(protocolVersionHeader) with a default fallback, validated against supportedProtocolVersions via slices.Contains.

Verdict: Not Vulnerable

Reviewed region:
[mcp/streamable.go]
```go
func (h *StreamableHTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// DNS rebinding protection: auto-enabled for localhost servers.
	// See: https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise
	if !h.opts.DisableLocalhostProtection && disablelocalhostprotection != "1" {
		if localAddr, ok := req.Context().Value(http.LocalAddrContextKey).(net.Addr); ok && localAddr != nil {
			if util.IsLoopback(localAddr.String()) && !util.IsLoopback(req.Host) {
				http.Error(w, fmt.Sprintf("Forbidden: invalid Host header %q", req.Host), http.StatusForbidden)
				return
			}
		}
	}

	// Allow multiple 'Accept' headers.
	// https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Accept#syntax
	accept := strings.Split(strings.Join(req.Header.Values("Accept"), ","), ",")
	var jsonOK, streamOK bool
	for _, c := range accept {
		switch strings.TrimSpace(c) {
		case "application/json", "application/*":
			jsonOK = true
		case "text/event-stream", "text/*":
			streamOK = true
		case "*/*":
			jsonOK = true
			streamOK = true
		}
	}

	if req.Method == http.MethodGet {
		if !streamOK {
			http.Error(w, "Accept must contain 'text/event-stream' for GET requests", http.StatusBadRequest)
			return
		}
	} else if (!jsonOK || !streamOK) && req.Method != http.MethodDelete { // TODO: consolidate with handling of http method below.
		http.Error(w, "Accept must contain both 'application/json' and 'text/event-stream'", http.StatusBadRequest)
		return
	}

	sessionID := req.Header.Get(sessionIDHeader)
	var sessInfo *sessionInfo
	if sessionID != "" {
		h.mu.Lock()
		sessInfo = h.sessions[sessionID]
		h.mu.Unlock()
		if sessInfo == nil && !h.opts.Stateless {
			// Unless we're in 'stateless' mode, which doesn't perform any Session-ID
			// validation, we require that the session ID matches a known session.
			//
			// In stateless mode, a temporary transport is be created below.
			http.Error(w, "session not found", http.StatusNotFound)
			return
		}
		// Prevent session hijacking: if the session was created with a user ID,
		// verify that subsequent requests come from the same user.
		if sessInfo != nil && sessInfo.userID != "" {
			tokenInfo := auth.TokenInfoFromContext(req.Context())
			if tokenInfo == nil || tokenInfo.UserID != sessInfo.userID {
				http.Error(w, "session user mismatch", http.StatusForbidden)
				return
			}
		}
	}

	if req.Method == http.MethodDelete {
		if sessionID == "" {
			http.Error(w, "Bad Request: DELETE requires an Mcp-Session-Id header", http.StatusBadRequest)
			return
		}
		if sessInfo != nil { // sessInfo may be nil in stateless mode
			// Closing the session also removes it from h.sessions, due to the
			// onClose callback.
			sessInfo.session.Close()
		}
		w.WriteHeader(http.StatusNoContent)
		return
	}

	switch req.Method {
	case http.MethodPost, http.MethodGet:
		if req.Method == http.MethodGet && (h.opts.Stateless || sessionID == "") {
			if h.opts.Stateless {
				// Per MCP spec: server MUST return 405 if it doesn't offer SSE stream.
				// In stateless mode, GET (SSE streaming) is not supported.
				// RFC 9110 §15.5.6: 405 responses MUST include Allow header.
				w.Header().Set("Allow", "POST")
				http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
			} else {
				// In stateful mode, GET is supported but requires a session ID.
				// This is a precondition error, similar to DELETE without session.
				http.Error(w, "Bad Request: GET requires an Mcp-Session-Id header", http.StatusBadRequest)
			}
			return
		}
	default:
		// RFC 9110 §15.5.6: 405 responses MUST include Allow header.
		if h.opts.Stateless {
			w.Header().Set("Allow", "POST")
		} else {
			w.Header().Set("Allow", "GET, POST, DELETE")
		}
		http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
		return
	}

	// [§2.7] of the spec (2025-06-18) states:
	//
	// "If using HTTP, the client MUST include the MCP-Protocol-Version:
	// <protocol-version> HTTP header on all subsequent requests to the MCP
	// server, allowing the MCP server to respond based on the MCP protocol
	// version.
	//
	// For example: MCP-Protocol-Version: 2025-06-18
	// The protocol version sent by the client SHOULD be the one negotiated during
	// initialization.
	//
	// For backwards compatibility, if the server does not receive an
	// MCP-Protocol-Version header, and has no other way to identify the version -
	// for example, by relying on the protocol version negotiated during
	// initialization - the server SHOULD assume protocol version 2025-03-26.
	//
	// If the server receives a request with an invalid or unsupported
	// MCP-Protocol-Version, it MUST respond with 400 Bad Request."
	//
	// Since this wasn't present in the 2025-03-26 version of the spec, this
	// effectively means:
	//  1. IF the client provides a version header, it must be a supported
	//     version.
	//  2. In stateless mode, where we've lost the state of the initialize
	//     request, we assume that whatever the client tells us is the truth (or
	//     assume 2025-03-26 if the client doesn't say anything).
	//
	// This logic matches the typescript SDK.
	//
	// [§2.7]: https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#protocol-version-header
	protocolVersion := req.Header.Get(protocolVersionHeader)
	if protocolVersion == "" {
		protocolVersion = protocolVersion20250326
	}
	if !slices.Contains(supportedProtocolVersions, protocolVersion) {
		http.Error(w, fmt.Sprintf("Bad Request: Unsupported protocol version (supported versions: %s)", strings.Join(supportedProtocolVersions, ",")), http.StatusBadRequest)
		return
	}

	if sessInfo == nil {
		server := h.getServer(req)
		if server == nil {
			// The getServer argument to NewStreamableHTTPHandler returned nil.
			http.Error(w, "no server available", http.StatusBadRequest)
			return
		}
		if sessionID == "" {
			// In stateless mode, sessionID may be nonempty even if there's no
			// existing transport.
			sessionID = server.opts.GetSessionID()
		}
		transport := &StreamableServerTransport{
			SessionID:    sessionID,
			Stateless:    h.opts.Stateless,
			EventStore:   h.opts.EventStore,
			jsonResponse: h.opts.JSONResponse,
			logger:       h.opts.Logger,
		}

		// Sessions without a session ID are also stateless: there's no way to
		// address them.
		stateless := h.opts.Stateless || sessionID == ""
		// To support stateless mode, we initialize the session with a default
		// state, so that it doesn't reject subsequent requests.
		var connectOpts *ServerSessionOptions
		if stateless {
			// Peek at the body to see if it is initialize or initialized.
			// We want those to be handled as usual.
			var hasInitialize, hasInitialized bool
			{
				// TODO: verify that this allows protocol version negotiation for
				// stateless servers.
				body, err := io.ReadAll(req.Body)
				if err != nil {
					http.Error(w, "failed to read body", http.StatusInternalServerError)
					return
				}
				req.Body.Close()

				// Reset the body so that it can be read later.
				req.Body = io.NopCloser(bytes.NewBuffer(body))

				msgs, _, err := readBatch(body)
				if err == nil {
					for _, msg := range msgs {
						if req, ok := msg.(*jsonrpc.Request); ok {
							switch req.Method {
							case methodInitialize:
								hasInitialize = true
							case notificationInitialized:
								hasInitialized = true
							}
						}
					}
				}
			}

			// If we don't have InitializeParams or InitializedParams in the request,
			// set the initial state to a default value.
			state := new(ServerSessionState)
			if !hasInitialize {
				state.InitializeParams = &InitializeParams{
					ProtocolVersion: protocolVersion,
				}
			}
			if !hasInitialized {
				state.InitializedParams = new(InitializedParams)
			}
			state.LogLevel = "info"
			connectOpts = &ServerSessionOptions{
				State: state,
			}
		} else {
			// Cleanup is only required in stateful mode, as transportation is
			// not stored in the map otherwise.
			connectOpts = &ServerSessionOptions{
				onClose: func() {
					h.mu.Lock()
					defer h.mu.Unlock()
					if info, ok := h.sessions[transport.SessionID]; ok {
						info.stopTimer()
						delete(h.sessions, transport.SessionID)
						if h.onTransportDeletion != nil {
							h.onTransportDeletion(transport.SessionID)
						}
					}
				},
			}
		}

		// Pass req.Context() here, to allow middleware to add context values.
		// The context is detached in the jsonrpc2 library when handling the
		// long-running stream.
		session, err := server.Connect(req.Context(), transport, connectOpts)
		if err != nil {
			http.Error(w, "failed connection", http.StatusInternalServerError)
			return
		}
		// Capture the user ID from the token info to enable session hijacking
		// prevention on subsequent requests.
		var userID string
		if tokenInfo := auth.TokenInfoFromContext(req.Context()); tokenInfo != nil {
			userID = tokenInfo.UserID
		}
		sessInfo = &sessionInfo{
			session:   session,
			transport: transport,
			userID:    userID,
		}

		if stateless {
			// Stateless mode: close the session when the request exits.
			defer session.Close() // close the fake session after handling the request
		} else {
			// Otherwise, save the transport so that it can be reused

			// Clean up the session when it times out.
			//
			// Note that the timer here may fire multiple times, but
			// sessInfo.session.Close is idempotent.
			if h.opts.SessionTimeout > 0 {
				sessInfo.timeout = h.opts.SessionTimeout
				sessInfo.timer = time.AfterFunc(sessInfo.timeout, func() {
					sessInfo.session.Close()
				})
			}
			h.mu.Lock()
			h.sessions[transport.SessionID] = sessInfo
			h.mu.Unlock()
			defer func() {
				// If initialization failed, clean up the session (#578).
				if session.InitializeParams() == nil {
					// Initialization failed.
					session.Close()
				}
			}()
		}
	}

	if req.Method == http.MethodPost {
		sessInfo.startPOST()
		defer sessInfo.endPOST()
	}

	sessInfo.transport.ServeHTTP(w, req)
}
```

Why it is not vulnerable: The DNS rebinding protection is correctly implemented. When the local address resolves to a loopback interface (util.IsLoopback(localAddr.String()) returns true), the code enforces that the Host header must also resolve to a loopback address (util.IsLoopback(req.Host) must return true). If the Host header does not resolve to loopback, the request is rejected with a 403 Forbidden response. The util.IsLoopback function properly handles multiple address formats: it uses net.SplitHostPort to extract the host component (handling addresses with ports), trims IPv6 brackets, checks for the 'localhost' literal, and uses netip.ParseAddr with ip.IsLoopback() for IP address validation. The protection is properly gated behind DisableLocalhostProtection and disablelocalhostprotection configuration flags, allowing administrators to explicitly disable it when needed (e.g., behind a reverse proxy). Invalid or unparseable addresses in util.IsLoopback return false, which is a safe default.

Security invariants:
- When localhost protection is not explicitly disabled (via h.opts.DisableLocalhostProtection or disablelocalhostprotection), the DNS rebinding guard must execute. Enforced by: if !h.opts.DisableLocalhostProtection && disablelocalhostprotection != "1"
- The local address must be successfully extracted from the request context and must be non-nil before applying the loopback check. Enforced by: if localAddr, ok := req.Context().Value(http.LocalAddrContextKey).(net.Addr); ok && localAddr != nil
- When the server is bound to a loopback interface, the Host header must also resolve to a loopback address. Enforced by: if util.IsLoopback(localAddr.String()) && !util.IsLoopback(req.Host) { return 403 }
- util.IsLoopback must correctly parse addresses with and without port numbers. Enforced by: net.SplitHostPort(addr) to extract host, with fallback handling when it fails
- util.IsLoopback must correctly identify loopback addresses in multiple formats: 'localhost' literal, IPv4 loopback (127.0.0.0/8), and IPv6 loopback (::1). Enforced by: host == "localhost" check and ip.IsLoopback() after netip.ParseAddr
- Invalid or unparseable addresses must not be treated as loopback (safe default). Enforced by: if err != nil { return false } in util.IsLoopback
- Session access is properly synchronized to prevent race conditions. Enforced by: h.mu.Lock()/h.mu.Unlock() around h.sessions map access
- Session hijacking is prevented by verifying user ID consistency. Enforced by: if tokenInfo == nil || tokenInfo.UserID != sessInfo.userID { return 403 }

Invariant verification:
- DNS rebinding protection is enabled by default and can only be explicitly disabled: holds=true. Evidence: The condition !h.opts.DisableLocalhostProtection && disablelocalhostprotection != "1" requires both the config field and the debug variable to explicitly disable the protection
- Local address extraction is safe and guards against missing context value: holds=true. Evidence: The type assertion with ok check: req.Context().Value(http.LocalAddrContextKey).(net.Addr); ok && localAddr != nil ensures the code only proceeds when a valid address is present
- Loopback detection correctly handles host:port format addresses: holds=true. Evidence: util.IsLoopback calls net.SplitHostPort(addr) which correctly separates host and port components, then operates on the host portion only
- Loopback detection correctly identifies localhost, IPv4 loopback, and IPv6 loopback: holds=true. Evidence: util.IsLoopback checks host == "localhost" for the literal, and uses netip.ParseAddr(host) followed by ip.IsLoopback() which covers 127.0.0.0/8 and ::1
- Unparseable addresses default to non-loopback (fail-safe): holds=true. Evidence: Both error paths in util.IsLoopback (net.SplitHostPort error and netip.ParseAddr error) lead to return false or fall through to return false
- Mismatched Host header on loopback interface results in request rejection: holds=true. Evidence: if util.IsLoopback(localAddr.String()) && !util.IsLoopback(req.Host) { http.Error(w, ..., http.StatusForbidden); return } rejects requests where local address is loopback but Host is not
- Session map access is protected by mutex: holds=true. Evidence: h.mu.Lock() before sessInfo = h.sessions[sessionID] and h.mu.Unlock() after; same pattern for write operations with h.sessions[transport.SessionID] = sessInfo

Residual risk notes: The DNS rebinding protection is skipped if the local address cannot be extracted from the request context (e.g., if the HTTP server does not populate http.LocalAddrContextKey). This is acceptable because the protection specifically applies to servers bound to loopback interfaces; if no local address information is available, the condition cannot be evaluated. The util.IsLoopback function does not perform DNS resolution on hostnames in the Host header, but this is correct behavior since the check is designed to detect when the Host header contains a non-loopback address literal or hostname that was not validated as loopback during the connection setup. The req.Host field is controlled by the client, but the IsLoopback check on it is the appropriate defense mechanism.

**Verdict: Not Vulnerable**

The DNS rebinding protection logic is correctly implemented and not bypassable through the supplied code paths.

**Evidence Analysis:**

1. **Protection Logic (lines 3-11)**
   - Checks if localhost protection is enabled (two conditions must both be false: `!h.opts.DisableLocalhostProtection` AND `disablelocalhostprotection != "1"`)
   - Extracts the server's local bind address from `http.LocalAddrContextKey`
   - If server is bound to loopback (`util.IsLoopback(localAddr.String())`) but request Host header is NOT loopback (`!util.IsLoopback(req.Host)`), rejects with 403

2. **IsLoopback Implementation (util/net.go)**
   - Handles both `host:port` format and bare host/IP
   - Recognizes "localhost" string literal
   - Parses IP addresses and checks `ip.IsLoopback()` (standard library method covering 127.0.0.0/8 and ::1)
   - Returns false on parse errors (fail-closed for protection)

3. **Attack Surface Assessment**
   - Attacker controls `req.Host` header
   - Attacker cannot control `localAddr` (set by Go's http.Server from actual socket binding)
   - Attacker cannot control `http.LocalAddrContextKey` context value (set by stdlib)

**Why This Prevents DNS Rebinding:**

When a server binds to 127.0.0.1:
- Legitimate local requests have `Host: localhost` or `Host: 127.0.0.1:port` → both pass `IsLoopback(req.Host)` → check passes
- DNS rebinding attack has `Host: attacker.com` → fails `IsLoopback(req.Host)` → 403 Forbidden

The protection correctly distinguishes between:
- Local client → local server (allowed)
- Remote attacker → local server via rebinding (blocked)

**Residual Considerations:**

1. **Bypass via configuration**: Protection can be disabled via `h.opts.DisableLocalhostProtection` or `disablelocalhostprotection` debug flag, but this is intentional operator control, not a vulnerability
2. **Context value availability**: Code checks `ok && localAddr != nil` before proceeding, gracefully handling missing context (protection simply doesn't apply if server isn't provably bound to loopback)
3. **IPv6 handling**: `IsLoopback` uses `netip.ParseAddr` which correctly handles IPv6 loopback (::1) and IPv4-mapped addresses

**Conclusion:**

The implementation follows the MCP specification's security best practices. The guard correctly prevents DNS rebinding attacks against localhost-bound servers by validating that the Host header matches the loopback nature of the server's bind address. No exploitable path exists in the supplied code.

```json
{
  "vulnerable": false,
  "cwe": null,
  "severity": null,
  "reviewed_region": "mcp/streamable.go:ServeHTTP:3-11",
  "vulnerable_region": null,
  "root_cause": null,
  "exploitability": null,
  "attack_preconditions": null,
  "impact": null,
  "non_vulnerable_reason": "DNS rebinding protection correctly validates that requests to loopback-bound servers contain loopback Host headers. Attacker controls req.Host but cannot control localAddr (set by Go stdlib from actual socket binding) or http.LocalAddrContextKey context value. When server binds to 127.0.0.1, legitimate local requests with Host: localhost/127.0.0.1 pass IsLoopback(req.Host) check, while DNS rebinding attacks with Host: attacker.com fail IsLoopback(req.Host) and receive 403. IsLoopback implementation correctly handles host:port format, localhost literal, IPv4/IPv6 loopback ranges via netip.ParseAddr and ip.IsLoopback(), and fails closed on parse errors.",
  "security_invariants": [
    "localAddr derived from http.LocalAddrContextKey reflects actual server socket binding, not attacker-controlled input",
    "IsLoopback(localAddr.String()) == true implies server bound to 127.0.0.0/8 or ::1",
    "IsLoopback(req.Host) == false for external domain names used in DNS rebinding",
    "Protection active when !h.opts.DisableLocalhostProtection && disablelocalhostprotection != \"1\"",
    "403 rejection occurs before any session or request processing when guard triggers"
  ],
  "invariant_verification": "localAddr sourced from http.Server.LocalAddrContextKey (stdlib-controlled). IsLoopback uses netip.ParseAddr and ip.IsLoopback() (stdlib methods covering RFC-defined loopback ranges). req.Host attacker-controlled but checked against loopback predicate. Guard placement at function entry prevents bypass via later code paths.",
  "residual_risk_notes": "Protection can be disabled via h.opts.DisableLocalhostProtection or disablelocalhostprotection debug flag, but this is intentional operator control. If localAddr context value is missing (ok == false or localAddr == nil), protection does not apply, but this requires non-standard http.Server configuration or middleware interference.",
  "call_path": "ServeHTTP (mcp/streamable.go) → http.LocalAddrContextKey (net/http) → util.IsLoopback (internal/util/net.go)"
}
```

Protection active when !h.opts.DisableLocalhostProtection && disablelocalhostprotection != "1"


Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: git.kernel.org/pub/scm/linux/kernel/git/stable/linux
Language: C
File: fs/notify/mark.c
Function: fsnotify_put_inode_ref

Call path: fsnotify_put_mark (fs/notify/mark.c) → fsnotify_drop_object (fs/notify/mark.c) → fsnotify_put_inode_ref (fs/notify/mark.c) → fsnotify_put_sb_watched_objects (fs/notify/mark.c) → generic_shutdown_super (fs/super.c)

### Primary Function

```c
static void fsnotify_put_sb_watched_objects(struct super_block *sb)
{
	atomic_long_t *watched_objects = fsnotify_sb_watched_objects(sb);

	/* the superblock can go away after this decrement */
	if (atomic_long_dec_and_test(watched_objects))
		wake_up_var(watched_objects);
}

static void fsnotify_get_sb_watched_objects(struct super_block *sb)
{
	atomic_long_inc(fsnotify_sb_watched_objects(sb));
}

static void fsnotify_get_inode_ref(struct inode *inode)
{
	ihold(inode);
	fsnotify_get_sb_watched_objects(inode->i_sb);
}

static void fsnotify_put_inode_ref(struct inode *inode)
{
	/* read ->i_sb before the inode can go away */
	struct super_block *sb = inode->i_sb;

	iput(inode);
	fsnotify_put_sb_watched_objects(sb);
}
```

### Cross-File Context

[fsnotify_put_sb_watched_objects — callee — fs/notify/mark.c:139-147]
```c
static void fsnotify_put_sb_watched_objects(struct super_block *sb)
{
	atomic_long_t *watched_objects = fsnotify_sb_watched_objects(sb);

	/* the superblock can go away after this decrement */
	if (atomic_long_dec_and_test(watched_objects))
		wake_up_var(watched_objects);
}
```

[fsnotify_get_sb_watched_objects — function — fs/notify/mark.c:134-137]
```c
static void fsnotify_get_sb_watched_objects(struct super_block *sb)
{
	atomic_long_inc(fsnotify_sb_watched_objects(sb));
}
```

[fsnotify_get_inode_ref — function — fs/notify/mark.c:145-150]
```c
static void fsnotify_get_inode_ref(struct inode *inode)
{
	ihold(inode);
	fsnotify_get_sb_watched_objects(inode->i_sb);
}
```

[fsnotify_drop_object — caller — fs/notify/mark.c:370-377]
```c
static void fsnotify_drop_object(unsigned int type, void *objp)
{
	if (!objp)
		return;
	/* Currently only inode references are passed to be dropped */
	if (WARN_ON_ONCE(type != FSNOTIFY_OBJ_TYPE_INODE))
		return;
	fsnotify_put_inode_ref(objp);
}
```

[fsnotify_sb_watched_objects — function — include/linux/fsnotify_backend.h:507-509]
```c
static inline atomic_long_t *fsnotify_sb_watched_objects(struct super_block *sb)
{
	return &fsnotify_sb_info(sb)->watched_objects[0];
}
```

[fsnotify_sb_info — struct — include/linux/fsnotify_backend.h:485-496]
```c
struct fsnotify_sb_info {
	struct fsnotify_mark_connector __rcu *sb_marks;
	atomic_long_t watched_objects[__FSNOTIFY_PRIO_NUM];
};
```

[__FSNOTIFY_PRIO_NUM — constant — include/linux/fsnotify_backend.h:187]
__FSNOTIFY_PRIO_NUM → 3  (include/linux/fsnotify_backend.h:187)

[fsnotify_group_prio — enum — include/linux/fsnotify_backend.h:183-188]
enum fsnotify_group_prio { FSNOTIFY_PRIO_NORMAL = 0, FSNOTIFY_PRIO_CONTENT, FSNOTIFY_PRIO_PRE_CONTENT, __FSNOTIFY_PRIO_NUM };

Control flow: fsnotify_put_inode_ref receives an inode pointer and executes a linear sequence: (1) reads inode->i_sb into local variable sb before any cleanup, (2) calls iput(inode) to drop the inode reference which may trigger inode deallocation, (3) calls fsnotify_put_sb_watched_objects(sb) to decrement the superblock's watched_objects atomic counter. Inside fsnotify_put_sb_watched_objects, if the counter reaches zero, it calls wake_up_var on the counter to wake waiters that may be blocking on superblock cleanup. The caller fsnotify_drop_object validates the object type and forwards the inode to fsnotify_put_inode_ref.

Data flow: The inode pointer enters fsnotify_put_inode_ref as the sole parameter. The superblock pointer is extracted from inode->i_sb and stored in local variable sb before iput(inode) is called. iput(inode) drops the inode reference count and may eventually free the inode structure. The sb pointer is then passed to fsnotify_put_sb_watched_objects, which accesses sb to locate the watched_objects atomic counter, decrements it, and conditionally wakes waiters. The pairing function fsnotify_get_inode_ref acquires references in the opposite order (inode hold then sb counter increment), ensuring balanced reference counting.

Verdict: Not Vulnerable

Reviewed region:
[fs/notify/mark.c]
```c
static void fsnotify_put_sb_watched_objects(struct super_block *sb)
{
	atomic_long_t *watched_objects = fsnotify_sb_watched_objects(sb);

	/* the superblock can go away after this decrement */
	if (atomic_long_dec_and_test(watched_objects))
		wake_up_var(watched_objects);
}

static void fsnotify_get_sb_watched_objects(struct super_block *sb)
{
	atomic_long_inc(fsnotify_sb_watched_objects(sb));
}

static void fsnotify_get_inode_ref(struct inode *inode)
{
	ihold(inode);
	fsnotify_get_sb_watched_objects(inode->i_sb);
}

static void fsnotify_put_inode_ref(struct inode *inode)
{
	/* read ->i_sb before the inode can go away */
	struct super_block *sb = inode->i_sb;

	iput(inode);
	fsnotify_put_sb_watched_objects(sb);
}
```

Why it is not vulnerable: The code correctly captures the superblock pointer (sb = inode->i_sb) before calling iput(inode), as explicitly noted by the comment 'read ->i_sb before the inode can go away'. Since iput(inode) may trigger inode deallocation which could cascade to superblock deallocation, reading inode->i_sb after iput would be a use-after-free. The current ordering ensures sb remains valid for the subsequent fsnotify_put_sb_watched_objects(sb) call, which only accesses the watched_objects array within the superblock. The atomic counter in fsnotify_put_sb_watched_objects protects against premature superblock deallocation by coordinating with waiters that hold the superblock.

Security invariants:
- The superblock pointer must be captured from inode->i_sb before any operation that may invalidate the inode structure. Enforced by: struct super_block *sb = inode->i_sb; appearing as the first statement before iput(inode).
- The watched_objects atomic counter must prevent the superblock from being freed while fsnotify_put_sb_watched_objects is accessing it. Enforced by: atomic_long_dec_and_test(watched_objects) which is paired with wake_up_var to coordinate with superblock teardown code that waits for this counter to reach zero.
- Reference acquisition and release must be symmetric to prevent counter leaks or premature deallocation. Enforced by: fsnotify_get_inode_ref calling ihold(inode) and fsnotify_get_sb_watched_objects, with fsnotify_put_inode_ref calling iput(inode) and fsnotify_put_sb_watched_objects in the corresponding reverse order.
- The superblock pointer must remain valid for the duration of the fsnotify_put_sb_watched_objects call. Enforced by: the sb variable being a local copy captured before iput(inode), and the atomic counter mechanism ensuring the superblock is not freed while this function is executing.

Invariant verification:
- Superblock pointer captured before potentially destructive inode release: holds=true. Evidence: struct super_block *sb = inode->i_sb; is the first operation in fsnotify_put_inode_ref, executed before iput(inode)
- Atomic counter protects against premature superblock deallocation during watched_objects access: holds=true. Evidence: atomic_long_dec_and_test(watched_objects) in fsnotify_put_sb_watched_objects decrements the counter atomically and only signals wake_up_var if counter reaches zero, coordinating with superblock teardown waiters
- Balanced reference counting between get and put operations: holds=true. Evidence: fsnotify_get_inode_ref pairs ihold(inode) + fsnotify_get_sb_watched_objects with fsnotify_put_inode_ref's iput(inode) + fsnotify_put_sb_watched_objects, ensuring matched increment/decrement of the watched_objects counter
- No dereference of inode after iput may have freed it: holds=true. Evidence: After iput(inode), only the locally-captured sb pointer is used in fsnotify_put_sb_watched_objects(sb); no further access to the inode occurs

Residual risk notes: The correctness of this pattern depends on all call paths that acquire inode references via fsnotify_get_inode_ref releasing them via fsnotify_put_inode_ref. If any code path acquires the sb watched_objects counter without holding a corresponding inode reference, or drops the inode reference without calling fsnotify_put_sb_watched_objects, the reference counting invariants could be violated. The behavior of the superblock teardown code that waits on the watched_objects counter is not visible in the supplied context, but the atomic coordination mechanism appears sound.

# Vulnerability Analysis: Use-After-Free in fsnotify_put_inode_ref

## Vulnerability Classification
**Use-After-Free (CWE-416)** - Accessing superblock pointer after the inode (and potentially the superblock itself) has been freed.

## Root Cause
The function reads `inode->i_sb` into a local variable `sb`, then calls `iput(inode)` which may free the inode, followed by `fsnotify_put_sb_watched_objects(sb)`. The comment "read ->i_sb before the inode can go away" acknowledges the inode may be freed but fails to address that the superblock itself may also be freed.

## Vulnerable Execution Path

1. `fsnotify_put_inode_ref` reads `sb = inode->i_sb`
2. `iput(inode)` is called, potentially:
   - Dropping the last inode reference
   - Triggering inode destruction
   - If this was the last active inode, potentially triggering superblock teardown via `generic_shutdown_super`
3. `fsnotify_put_sb_watched_objects(sb)` dereferences the now-freed `sb` pointer to access `sb->s_fsnotify_info->watched_objects`

## Attack Preconditions

- The `iput(inode)` call must drop the last reference to the inode
- The inode must be the last object keeping the superblock alive
- The superblock must be in a state where it can be freed (e.g., unmounting filesystem)
- Race condition timing: the superblock teardown must complete between `iput()` and the `fsnotify_put_sb_watched_objects()` call

## Data Flow Evidence

**Reference counting imbalance:**
- `fsnotify_get_inode_ref`: increments both inode refcount (`ihold`) AND sb watched_objects counter
- `fsnotify_put_inode_ref`: decrements inode refcount (`iput`) then sb watched_objects counter
- The sb watched_objects counter is meant to keep the superblock alive, but the decrement happens AFTER the iput that could trigger sb destruction

**Critical ordering flaw:**
The comment in `fsnotify_put_sb_watched_objects` states "the superblock can go away after this decrement", but the code accesses the superblock DURING the decrement via `fsnotify_sb_watched_objects(sb)` which dereferences `sb->s_fsnotify_info`.

## Exploitability

**Medium-High** - Requires specific timing:
- Attacker needs to trigger filesystem unmount while fsnotify marks are being released
- The race window is narrow but deterministic in certain unmount scenarios
- Successful exploitation leads to kernel memory corruption

## Impact

- **Kernel memory corruption** from accessing freed superblock structure
- **Potential privilege escalation** if attacker can control freed memory contents
- **Kernel crash/denial of service** most likely outcome

## Correct Fix Pattern

The superblock reference must be held across the `iput()` call. The watched_objects counter should be decremented BEFORE the iput, or an explicit superblock reference should be taken:

```c
static void fsnotify_put_inode_ref(struct inode *inode)
{
    struct super_block *sb = inode->i_sb;

    fsnotify_put_sb_watched_objects(sb);  // decrement BEFORE iput
    iput(inode);
}
```

Or the reference counting protocol needs redesign to ensure the superblock cannot be freed while watched_objects references exist.

## Verdict

**VULNERABLE** - Use-after-free due to incorrect reference counting order. The superblock pointer is accessed after the operation that may free both the inode and superblock.

```json
{
  "vulnerable": true,
  "cwe": "CWE-416",
  "severity": "HIGH",
  "reviewed_region": "fs/notify/mark.c:fsnotify_put_inode_ref",
  "vulnerable_region": "fs/notify/mark.c:fsnotify_put_inode_ref lines accessing sb after iput(inode)",
  "root_cause": "The function reads inode->i_sb into local variable sb, calls iput(inode) which may free the inode and trigger superblock destruction, then dereferences sb in fsnotify_put_sb_watched_objects(sb). The watched_objects counter is meant to keep the superblock alive but is decremented AFTER the iput() that could trigger superblock teardown via generic_shutdown_super. The fsnotify_put_sb_watched_objects function accesses sb->s_fsnotify_info->watched_objects[0] through fsnotify_sb_watched_objects(sb), creating use-after-free if sb was freed during iput.",
  "exploitability": "MEDIUM_HIGH",
  "attack_preconditions": [
    "iput(inode) must drop the last reference to the inode",
    "The inode must be among the last objects keeping the superblock alive",
    "Filesystem must be in unmount or teardown state where superblock can be freed",
    "Race timing: superblock destruction must complete between iput() and fsnotify_put_sb_watched_objects() accessing sb->s_fsnotify_info"
  ],
  "impact": "Kernel memory corruption from dereferencing freed superblock structure. Most likely outcome is kernel crash/denial of service. Potential for privilege escalation if attacker can control freed memory contents and influence subsequent allocations. The atomic_long_dec_and_test operation on freed memory could corrupt kernel heap metadata.",
  "non_vulnerable_reason": null,
  "security_invariants": null,
  "invariant_verification": null,
  "residual_risk_notes": "The reference counting protocol shows asymmetry: fsnotify_get_inode_ref increments both inode refcount (ihold) and sb watched_objects counter, while fsnotify_put_inode_ref decrements inode refcount first then sb counter. The comment 'the superblock can go away after this decrement' in fsnotify_put_sb_watched_objects acknowledges sb lifetime but the decrement itself requires dereferencing sb. Correct fix requires decrementing watched_objects BEFORE iput(inode) to maintain superblock lifetime guarantee.",
  "call_path": "fsnotify_put_mark → fsnotify_drop_object → fsnotify_put_inode_ref → fsnotify_put_sb_watched_objects → (potential) generic_shutdown_super"
}
```


Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: github.com/chamilo/chamilo-lms
Language: PHP
File: main/document/document.php
Function: document_listing_display

Call path: document.php (main/document/document.php) → DocumentManager::get_document_data_by_id (main/document/document.php) → document_listing_display (main/document/document.php)

### Primary Function

```php
<?php
// Document title with link and comment
$titleWithLink = $link.$session_img.'<br />'.$invisibility_span_open;
$commentText = nl2br(htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset));
if (!empty($commentText)) {
    $titleWithLink .= '<em>'.$commentText.'</em>';
}
$titleWithLink .= $invisibility_span_close.$user_link;
$row[] = $titleWithLink;
```

### Cross-File Context

[Security::remove_XSS — method — main/inc/lib/security.lib.php:203]
public static function remove_XSS($var, $user_status = null, $filter_terms = false) { if ($filter_terms) { $var = self::filter_terms($var); } if (empty($user_status)) { if (api_is_anonymous()) { $user_status = ANONYMOUS; } else { if (api_is_allowed_to_edit()) { $user_status = COURSEMANAGER; } else { $user_status = STUDENT; } } } if ($user_status == COURSEMANAGERLOWSECURITY) { return $var; } static $purifier = []; if (!isset($purifier[$user_status])) { $cache_dir = api_get_path(SYS_ARCHIVE_PATH).'Serializer'; if (!file_exists($cache_dir)) { $mode = api_get_permissions_for_new_directories(); mkdir($cache_dir, $mode); } $config = HTMLPurifier_Config::createDefault(); $config->set('Cache.SerializerPath', $cache_dir); $config->set('Core.Encoding', api_get_system_encoding()); $config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); $config->set('HTML.MaxImgLength', '2560'); $config->set('HTML.TidyLevel', 'light'); $config->set('Core.ConvertDocumentToFragment', false); $config->set('Core.RemoveProcessingInstructions', true); if (api_get_setting('enable_iframe_inclusion') == 'true') { $config->set('Filter.Custom', [new AllowIframes()]); } $config->set('Attr.AllowedFrameTargets', ['_blank', '_top', '_self', '_parent']); if ($user_status == STUDENT) { global $allowed_html_student; $config->set('HTML.SafeEmbed', true); $config->set('HTML.SafeObject', true); $config->set('Filter.YouTube', true); $config->set('HTML.FlashAllowFullScreen', true); $config->set('HTML.Allowed', $allowed_html_student); } elseif ($user_status == COURSEMANAGER) { global $allowed_html_teacher; $config->set('HTML.SafeEmbed', true); $config->set('HTML.SafeObject', true); $config->set('Filter.YouTube', true); $config->set('HTML.FlashAllowFullScreen', true); $config->set('HTML.Allowed', $allowed_html_teacher); } else { global $allowed_html_anonymous; $config->set('HTML.Allowed', $allowed_html_anonymous); } $config->set('Attr.EnableID', true); $config->set('CSS.AllowImportant', true); $config->set('CSS.AllowTricky', true); $config->set('CSS.Proprietary', true); $config->set('URI.AllowedSchemes', ['http' => true, 'https' => true, 'mailto' => true, 'ftp' => true, 'nntp' => true, 'news' => true, 'data' => true]); $config->set('HTML.SafeIframe', true); $config->set('HTML.DefinitionID', 'html5-definitions'); $config->set('HTML.DefinitionRev', 1); if ($def = $config->maybeGetRawHTMLDefinition()) { $def->addElement('video', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', ['src' => 'URI', 'type' => 'Text', 'width' => 'Length', 'height' => 'Length', 'poster' => 'URI', 'preload' => 'Enum#auto,metadata,none', 'controls' => 'Bool']); $def->addElement('audio', 'Block', 'Optional: (source, Flow) | (Flow, source) | Flow', 'Common', ['autoplay' => 'Bool', 'src' => 'URI', 'loop' => 'Bool', 'preload' => 'Enum#auto,metadata,none', 'controls' => 'Bool', 'muted' => 'Bool']); $def->addElement('source', 'Block', 'Flow', 'Common', ['src' => 'URI', 'type' => 'Text']); } $purifier[$user_status] = new HTMLPurifier($config); } if (is_array($var)) { return $purifier[$user_status]->purifyArray($var); } else { return $purifier[$user_status]->purify($var); } }

Control flow: User requests document listing -> document.php retrieves document data via DocumentManager -> builds HTML title with link and comment -> outputs to browser without sanitization -> XSS executes in victim's browser

Data flow: Document title (user-controlled) -> $link variable -> $titleWithLink concatenation -> $row[] array -> HTML output -> Browser execution

Verdict: Vulnerable
Vulnerable region:
[main/document/document.php]
```php
);

            // Document title with link and comment
            $titleWithLink = $link.$session_img.'<br />'.$invisibility_span_open;
            $commentText = nl2br(htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset));
            if (!empty($commentText)) {
                $titleWithLink .= '<em>'.$commentText.'</em>';
            }
```
CWE: CWE-79
Severity: MEDIUM

Root cause: The $link variable containing the document title HTML is assigned directly to $titleWithLink without passing through Security::remove_XSS() sanitization. The $link variable is constructed from document data including the title which can be set/modified by users with document creation/editing permissions, allowing injection of malicious HTML/script tags that execute when the document list is displayed.

Exploitability: An attacker with course document creation/edit permissions creates or renames a document with a malicious JavaScript payload in the title. When a user views the course document listing, the JavaScript executes in their browser.

Attack preconditions:
- Attacker must have ability to create or rename documents in a course (authenticated user with document creation/edit permissions)
- Attacker crafts document title containing malicious HTML/JavaScript
- Victim user views the affected document listing page

Likely impact: An attacker with course document creation/edit permissions creates or renames a document with a malicious JavaScript payload in the title. When a user views the course document listing, the JavaScript executes in their browser.

);

            // Document title with link and comment
            $titleWithLink = $link.$session_img.'
'.$invisibility_span_open;
            $commentText = nl2br(htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset));
            if (!empty($commentText)) {
                $titleWithLink .= ''.$commentText.'';
            }

**Verdict: NOT VULNERABLE**

The code uses `htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset)` to encode the comment text before output, which neutralizes XSS by converting HTML special characters (`<`, `>`, `&`, `"`, `'`) to their entity equivalents.

**Evidence:**

1. **Input sanitization present:** The comment field is passed through `htmlspecialchars()` with `ENT_QUOTES` flag, which encodes both double and single quotes
2. **Additional newline handling:** `nl2br()` is applied after encoding, which only converts `\n` to `<br />` tags — it doesn't introduce new XSS vectors since the HTML characters are already encoded
3. **Output context:** The result is wrapped in `<em>` tags and concatenated into `$titleWithLink`, which is later assigned to `$row[]` for display

**Attack surface analysis:**

- An attacker controlling `$document_data['comment']` could inject: `<script>alert(1)</script>`
- After `htmlspecialchars()`: `<script>alert(1)</script>`
- After `nl2br()`: `<script>alert(1)</script>` (unchanged, no newlines)
- Final output in HTML: Renders as literal text, not executed

**Other variables in the concatenation:**

- `$link`, `$session_img`, `$invisibility_span_open/close`, `$user_link` are not shown in the supplied code
- If any of these variables contain unsanitized user input, they could introduce XSS
- However, the **candidate function** itself (the comment handling) is properly protected

**Cross-file context note:**

The `Security::remove_XSS()` method using HTMLPurifier is provided but not invoked in this code path. The simpler `htmlspecialchars()` is sufficient for plain text output in this context.

**Residual uncertainty:**

Cannot verify sanitization of `$link`, `$session_img`, `$invisibility_span_open`, `$invisibility_span_close`, or `$user_link` without their definitions. If vulnerable, the issue would be in those variables, not in the comment handling shown here.

```json
{
  "vulnerable": false,
  "cwe": null,
  "severity": "none",
  "reviewed_region": "main/document/document.php:document_listing_display - comment display logic lines constructing $titleWithLink",
  "vulnerable_region": null,
  "root_cause": null,
  "exploitability": "not_exploitable",
  "attack_preconditions": null,
  "impact": null,
  "non_vulnerable_reason": "The comment field undergoes htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset) encoding before output. This converts <, >, &, \", and ' to HTML entities, neutralizing script injection. The subsequent nl2br() only converts newlines to <br /> tags after encoding is complete, preserving the entity encoding. Any HTML/JavaScript in the comment renders as literal text.",
  "security_invariants": [
    "htmlspecialchars() with ENT_QUOTES encodes all HTML special characters and quotes before output",
    "nl2br() is applied post-encoding and only affects newline characters, not HTML entities",
    "Encoded entities remain encoded through concatenation into $titleWithLink and assignment to $row[]"
  ],
  "invariant_verification": "Direct code inspection confirms htmlspecialchars() is called with ENT_QUOTES flag on $document_data['comment'] before any output context. The encoding transformation is irreversible in the output path shown.",
  "residual_risk_notes": "Cannot verify sanitization of $link, $session_img, $invisibility_span_open, $invisibility_span_close, or $user_link as their definitions are not provided. If these variables contain unsanitized user-controlled data, XSS may exist in those concatenation points. The vulnerability would be in those variables' construction, not in the comment handling reviewed here.",
  "call_path": "document.php → DocumentManager::get_document_data_by_id → document_listing_display"
}
```

The comment field undergoes htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset) encoding before output. This converts <, >, &, ", and ' to HTML entities, neutralizing script injection. The subsequent nl2br() only converts newlines to <br /> tags after encoding is complete, preserving the entity encoding. Any HTML/JavaScript in the comment renders as literal text.