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/ImageMagick/ImageMagick
Language: C
File: coders/wpg.c
Function: ExtractPostscript

Call path: ReadWPGImage (coders/wpg.c) → ExtractPostscript (coders/wpg.c) → GetMagicInfo (MagickCore/magic.c) → ReadImage (MagickCore/image.c)

### Primary Function

```c
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
  MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
  char
    postscript_file[MaxTextExtent];

  const MagicInfo
    *magic_info;

  FILE
    *ps_file;

  ImageInfo
    *clone_info;

  Image
    *image2;

  unsigned char
    magick[2*MaxTextExtent];

  if ((clone_info=CloneImageInfo(image_info)) == NULL)
    return(image);
  clone_info->blob=(void *) NULL;
  clone_info->length=0;

  /* Obtain temporary file */
  (void) AcquireUniqueFilename(postscript_file);
  ps_file=fopen_utf8(postscript_file,"wb");
  if (ps_file == (FILE *) NULL)
    goto FINISH;

  /* Copy postscript to temporary file */
  (void) SeekBlob(image,PS_Offset,SEEK_SET);
  (void) ReadBlob(image, 2*MaxTextExtent, magick);

  (void) SeekBlob(image,PS_Offset,SEEK_SET);
  while(PS_Size-- > 0)
    {
      (void) fputc(ReadBlobByte(image),ps_file);
    }
  (void) fclose(ps_file);

    /* Detect file format - Check magic.mgk configuration file. */
  magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
  if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
  /*     printf("Detected:%s  \n",magic_info->name); */
  if(exception->severity != UndefinedException) goto FINISH_UNL;
  if(magic_info->name == (char *) NULL) goto FINISH_UNL;

  (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);

    /* Read nested image */
  /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
  FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
  image2=ReadImage(clone_info,exception);

  if (!image2)
    goto FINISH_UNL;

  /*
    Replace current image with new image while copying base image
    attributes.
  */
  (void) CopyMagickString(image2->filename,image->filename,MaxTextExtent);
  (void) CopyMagickString(image2->magick_filename,image->magick_filename,MaxTextExtent);
  (void) CopyMagickString(image2->magick,image->magick,MaxTextExtent);
  image2->depth=image->depth;
  DestroyBlob(image2);
  image2->blob=ReferenceBlob(image->blob);

  if ((image->rows == 0) || (image->columns == 0))
    DeleteImageFromList(&image);

  AppendImageToList(&image,image2);

 FINISH_UNL:
  (void) RelinquishUniqueFileResource(postscript_file);
 FINISH:
  DestroyImageInfo(clone_info);
  return(image);
}
```

### Cross-File Context

[MaxTextExtent — macro — MagickCore/method-attribute.h:80]
MaxTextExtent → MagickPathExtent  (MagickCore/method-attribute.h:80)

[MagickPathExtent — macro — MagickCore/method-attribute.h:79]
MagickPathExtent → 4096  (MagickCore/method-attribute.h:79)

[_MagicInfo — struct — MagickCore/magic.c:82]
```c
struct _MagicInfo
{
  char
    *name;

  unsigned char
    *magic;

  size_t
    length;

  MagickOffsetType
    offset;

  MagickBooleanType
    skip_spaces;

  size_t
    signature;
};
```

[_ImageInfo — struct — MagickCore/image.h:358]
```c
struct _ImageInfo
{
  ...
  char
    magick[MagickPathExtent],    /* image file format (file magick) */
  ...
};
```

[GetMagicInfo — callee — MagickCore/magic.c:303]
```c
MagickExport const MagicInfo *GetMagicInfo(const unsigned char *magic,
  const size_t length,ExceptionInfo *exception)
```

Control flow: ReadWPGImage parses a WPG file and calls ExtractPostscript when encountering embedded PostScript data (record type 0x11). ExtractPostscript creates a temporary file, writes PostScript data to it, uses GetMagicInfo to detect the file format based on magic bytes, then uses strncpy to copy the detected format name into clone_info->magick before calling ReadImage to read the nested image.

Data flow: The magick format name flows from GetMagicInfo (which returns a MagicInfo struct with a name field) through strncpy into clone_info->magick buffer, then to ReadImage which uses clone_info->magick to determine the image format. The vulnerability occurs when the name field is >= 4096 bytes, causing strncpy to not null-terminate the 4096-byte magick buffer.

Verdict: Vulnerable
Vulnerable region:
[coders/wpg.c]
```c
/*     printf("Detected:%s  \n",magic_info->name); */
```
CWE: CWE-189
Severity: MEDIUM

Root cause: The strncpy at line 806 in coders/wpg.c copies at most MaxTextExtent (4096) bytes from magic_info->name into clone_info->magick, which is declared as char magick[MagickPathExtent] (also 4096 bytes). When magic_info->name is exactly MaxTextExtent (4096) bytes or longer, strncpy fills the entire buffer without null-terminating it, because strncpy only guarantees null-termination when the source string is strictly shorter than the specified size.

Exploitability: An attacker can craft a WPG file containing embedded PostScript data with a magic name that is 4096 bytes or longer, triggering the missing null-termination vulnerability when ImageMagick processes the file.

Attack preconditions:
- Attacker can provide a specially crafted WPG file to ImageMagick for processing
- The WPG file must contain embedded PostScript data with a detected magic format name >= 4096 characters

Likely impact: An attacker can craft a WPG file containing embedded PostScript data with a magic name that is 4096 bytes or longer, triggering the missing null-termination vulnerability when ImageMagick processes the file.

ReadWPGImage ExtractPostscript GetMagicInfo ReadImage

Control flow: ReadWPGImage parses WPG file format, detects embedded PostScript content, and calls ExtractPostscript to extract and process the embedded PS data. ExtractPostscript creates a temporary file, copies PS data, detects the format via GetMagicInfo, and uses strncpy to copy the magic name into clone_info->magick buffer.

Data flow: magic_info->name (from GetMagicInfo parsing magic.mgk) -> strncpy -> clone_info->magick (char[4096]). When magic_info->name >= 4096 bytes, strncpy writes exactly 4096 bytes without null-terminating, potentially causing overflow if subsequent operations assume null-termination.

Verdict: Vulnerable
Vulnerable region:
[coders/wpg.c]
```c
(void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);
```
CWE: CWE-120
Severity: MEDIUM

Root cause: strncpy(clone_info->magick, magic_info->name, MaxTextExtent) copies up to MaxTextExtent (4096) bytes from magic_info->name into clone_info->magick which is char magick[MagickPathExtent] (4096 bytes). When the source string length equals or exceeds 4096 bytes, strncpy writes exactly 4096 bytes without adding a null terminator, potentially causing a buffer overflow when the destination is used as a null-terminated string.

Exploitability: An attacker can craft a WPG file containing embedded PostScript with a magic name string that is 4096 or more bytes long. When ImageMagick processes this file, the strncpy call will overflow the magick buffer by at least one byte (the missing null terminator).

Attack preconditions:
- Attacker must provide a specially crafted WPG file to ImageMagick for processing
- The embedded PostScript section must have a magic name >= 4096 bytes as detected by GetMagicInfo

Likely impact: An attacker can craft a WPG file containing embedded PostScript with a magic name string that is 4096 or more bytes long. When ImageMagick processes this file, the strncpy call will overflow the magick buffer by at least one byte (the missing null terminator).

```json
{
  "vulnerable": true,
  "cwe": "CWE-120",
  "severity": "MEDIUM",
  "reviewed_region": {
    "file_path": "coders/wpg.c",
    "symbol": "ExtractPostscript",
    "code": "(void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);"
  },
  "vulnerable_region": {
    "file_path": "coders/wpg.c",
    "symbol": "ExtractPostscript",
    "code": "(void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);"
  },
  "root_cause": "strncpy(clone_info->magick, magic_info->name, MaxTextExtent) copies up to MaxTextExtent (4096) bytes from magic_info->name into clone_info->magick which is char magick[MagickPathExtent] (4096 bytes). When the source string length equals or exceeds 4096 bytes, strncpy writes exactly 4096 bytes without adding a null terminator, potentially causing a buffer overflow when the destination is used as a null-terminated string.",
  "exploitability": "An attacker can craft a WPG file containing embedded PostScript with a magic name string that is 4096 or more bytes long. When ImageMagick processes this file, the strncpy call will overflow the magick buffer by at least one byte (the missing null terminator).",
  "attack_preconditions": [
    "Attacker must provide a specially crafted WPG file to ImageMagick for processing",
    "The embedded PostScript section must have a magic name >= 4096 bytes as detected by GetMagicInfo"
  ],
  "impact": "An attacker can craft a WPG file containing embedded PostScript with a magic name string that is 4096 or more bytes long. When ImageMagick processes this file, the strncpy call will overflow the magick buffer by at least one byte (the missing null terminator).",
  "non_vulnerable_reason": null,
  "security_invariants": [
    "strncpy should ensure null termination or use safer alternative"
  ],
  "invariant_verification": [
    "strncpy does not guarantee null termination when source length >= n"
  ],
  "residual_risk_notes": "other strncpy calls in codebase may have similar issues",
  "call_path": [
    "ReadWPGImage",
    "ExtractPostscript",
    "GetMagicInfo",
    "ReadImage"
  ]
}
```


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/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];

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: 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.

Control flow: The function begins with bounds validation of the resource index against RLIM_NLIMITS, returning -EINVAL if out of range. It then applies a Spectre mitigation mask to the index. If new_rlim is provided, it validates that rlim_cur <= rlim_max and that RLIMIT_NOFILE max does not exceed sysctl_nr_open. The function acquires a task lock, performs a capability check (CAP_SYS_RESOURCE) if increasing rlim_max, and invokes the security_task_setrlimit hook. On success, it copies values to old_rlim and updates the rlim array entry. After releasing the lock, if the operation succeeded and the resource is RLIMIT_CPU with a finite limit, it calls update_rlimit_cpu. All error paths return early with appropriate error codes (-EINVAL, -EPERM).

Data flow: The resource index from user input is validated against RLIM_NLIMITS (16), then passed through array_index_nospec to create a speculation-resistant masked value. This masked index is used to compute the rlim pointer via tsk->signal->rlim + resource, where rlim is an array of 16 struct rlimit entries. If new_rlim is non-NULL, its fields are validated and then copied to *rlim. The old_rlim output parameter receives the previous *rlim value before the update. The capability check and security hook operate on the validated resource index and new_rlim values.

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 array access `rlim = tsk->signal->rlim + resource` is protected by two complementary mechanisms: (1) a bounds check `if (resource >= RLIM_NLIMITS) return -EINVAL;` that prevents out-of-bounds access in normal execution, and (2) `resource = array_index_nospec(resource, RLIM_NLIMITS);` which applies a speculation-resistant mask to the index. The array_index_nospec macro computes a mask via array_index_mask_nospec that returns all 1s when index < size and all 0s otherwise, then ANDs this mask with the index. The OPTIMIZER_HIDE_VAR(index) call prevents the compiler from optimizing away the mask computation based on the prior bounds check. This ensures that even under speculative execution where the bounds check might be bypassed, the masked index will be zeroed if it was actually out of bounds, preventing speculative out-of-bounds array access.

Security invariants:
- The resource index must be less than RLIM_NLIMITS (16) for valid array access — enforced by `if (resource >= RLIM_NLIMITS) return -EINVAL;`
- The resource index must be speculation-resistant when used for array indexing — enforced by `resource = array_index_nospec(resource, RLIM_NLIMITS);` which masks the index to zero if it exceeds the array bounds
- The rlim array has exactly RLIM_NLIMITS elements — defined as `struct rlimit rlim[RLIM_NLIMITS]` in the signal structure
- The new limit's rlim_cur must not exceed rlim_max — enforced by `if (new_rlim->rlim_cur > new_rlim->rlim_max) return -EINVAL;`
- Increasing rlim_max requires CAP_SYS_RESOURCE capability — enforced by the capable() check before allowing the increase
- The task must be properly locked during rlim modification — enforced by task_lock/task_unlock around the critical section

Invariant verification:
- Bounds validation of resource index before array access: holds=true. Evidence: if (resource >= RLIM_NLIMITS) return -EINVAL;
- Spectre v1 mitigation on array index used for pointer arithmetic: holds=true. Evidence: resource = array_index_nospec(resource, RLIM_NLIMITS); applies a mask via array_index_mask_nospec that zeroes the index under speculation if it exceeds bounds, with OPTIMIZER_HIDE_VAR preventing compiler elimination
- Array size matches bounds constant: holds=true. Evidence: rlim is declared as struct rlimit rlim[RLIM_NLIMITS] with RLIM_NLIMITS defined as 16, matching the bounds check and nospec size parameter
- New limit validity (cur <= max): holds=true. Evidence: if (new_rlim->rlim_cur > new_rlim->rlim_max) return -EINVAL;
- Privilege check for raising hard limits: holds=true. Evidence: if (new_rlim->rlim_max > rlim->rlim_max && !capable(CAP_SYS_RESOURCE)) retval = -EPERM;

Residual risk notes: The security_task_setrlimit hook is a LSM callback whose behavior depends on loaded security modules; this is expected kernel design. The update_rlimit_cpu call for RLIMIT_CPU handling is only reached after successful rlim update and has its own internal guards. The bounds check and nospec mitigation are correctly ordered and both present, with no gap between them that could be exploited.


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.

Control flow: The ServeHTTP function begins with DNS rebinding protection: if localhost protection is not disabled and the server's local address is a loopback address, it validates that the Host header also resolves to a loopback address, returning 403 if not. The function then parses Accept headers to determine allowed response types, validates HTTP method compatibility (GET requires streamOK, POST/GET require both jsonOK and streamOK, DELETE is exempt), and checks session ID validity. For DELETE requests, it validates session ID presence, closes the session, and returns 204. For POST/GET, it validates method-specific preconditions (stateless mode rejects GET, stateful mode requires session ID). Protocol version is validated against supported versions. If no session exists, a new StreamableServerTransport is created, the server is connected, and the session is stored (stateful) or deferred-closed (stateless). Finally, the request is delegated to sessInfo.transport.ServeHTTP.

Data flow: The req parameter carries the incoming HTTP request. The local address is extracted via req.Context().Value(http.LocalAddrContextKey) and cast to net.Addr. The Host header is accessed via req.Host. Both are passed to util.IsLoopback() for comparison. The IsLoopback function splits the address into host and port, checks for the literal string "localhost", and falls back to netip.ParseAddr followed by ip.IsLoopback() for IP-based validation. The session ID from req.Header.Get(sessionIDHeader) is looked up in h.sessions under mutex protection. User ID validation compares auth.TokenInfoFromContext(req.Context()).UserID against sessInfo.userID. Protocol version from req.Header.Get(protocolVersionHeader) defaults to protocolVersion20250326 if absent and is validated against supportedProtocolVersions.

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 properly implemented. When the server listens on a loopback address (checked via util.IsLoopback(localAddr.String())), the Host header is validated to also be a loopback address (checked via util.IsLoopback(req.Host)). If the Host header is not loopback while the server is on loopback, the request is rejected with HTTP 403 Forbidden. The IsLoopback utility correctly handles multiple address formats: literal 'localhost', IPv4 loopback (127.0.0.0/8 range via ip.IsLoopback()), and IPv6 loopback (::1 via ip.IsLoopback()). Non-IP hostnames that aren't 'localhost' correctly fail the IsLoopback check, preventing DNS rebinding via attacker-controlled hostnames. The protection can only be intentionally disabled via explicit configuration (h.opts.DisableLocalhostProtection) or a debug flag, which is a deliberate design choice.

Security invariants:
- When the server binds to a loopback address, the Host header must resolve to a loopback address; enforced by: util.IsLoopback(localAddr.String()) && !util.IsLoopback(req.Host) returning 403
- The IsLoopback function must correctly identify all loopback address formats; enforced by: checking host == "localhost", then falling back to netip.ParseAddr(host) followed by ip.IsLoopback()
- The local address used for comparison must be the actual server binding address; enforced by: req.Context().Value(http.LocalAddrContextKey) which is populated by the net/http server
- The protection check must execute before any request processing; enforced by: the check appears at the very start of ServeHTTP, before session handling, method validation, or body parsing
- Session hijacking prevention must validate user identity on subsequent requests; enforced by: comparing auth.TokenInfoFromContext(req.Context()).UserID against sessInfo.userID and returning 403 on mismatch

Invariant verification:
- Loopback Host header validation when server is on loopback: holds=true. Evidence: if util.IsLoopback(localAddr.String()) && !util.IsLoopback(req.Host) { http.Error(w, fmt.Sprintf("Forbidden: invalid Host header %q", req.Host), http.StatusForbidden); return }
- IsLoopback correctly identifies IPv4 loopback addresses: holds=true. Evidence: ip, err := netip.ParseAddr(host) followed by return ip.IsLoopback() - Go's netip.IP.IsLoopback() returns true for 127.0.0.0/8
- IsLoopback correctly identifies IPv6 loopback addresses: holds=true. Evidence: netip.ParseAddr handles IPv6 format including bracket notation, and ip.IsLoopback() returns true for ::1
- IsLoopback rejects non-loopback hostnames: holds=true. Evidence: host == "localhost" check followed by netip.ParseAddr(host) which fails for non-IP hostnames, returning false
- Protection executes before request processing: holds=true. Evidence: The DNS rebinding check block is the first code executed in ServeHTTP, before Accept header parsing, method validation, session handling, and body reading
- Protection can be disabled only by explicit configuration: holds=true. Evidence: if !h.opts.DisableLocalhostProtection && disablelocalhostprotection != "1" - both conditions must be true to skip the check

Residual risk notes: The IsLoopback function relies on netip.ParseAddr for IP validation, which does not perform DNS resolution. This is correct behavior for this use case since we want to reject hostnames that don't explicitly indicate loopback. However, if a future attacker could manipulate the localAddr obtained from http.LocalAddrContextKey (which is populated by the net/http server based on actual socket binding), the protection could be bypassed. This would require compromising the underlying network stack, which is outside the scope of application-level defenses. Additionally, the disablelocalhostprotection debug flag provides a mechanism to bypass protection, but this requires explicit configuration and is intended for debugging purposes only.


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.'';
            }

Control flow: The function constructs an HTML string `$titleWithLink` by concatenating `$link`, `$session_img`, `$invisibility_span_open`, an optional comment block, `$invisibility_span_close`, and `$user_link`. The comment block is conditionally added only when `$document_data['comment']` is non-empty. The final string is appended to `$row[]`.

Data flow: The user-controlled input `$document_data['comment']` flows through `htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset)` which encodes HTML special characters. The encoded result is then passed to `nl2br()` for newline conversion. The fully processed comment is wrapped in `<em>` tags and concatenated into the HTML output string `$titleWithLink`, which is stored in `$row[]`.

Verdict: Not Vulnerable

Reviewed region:
[main/document/document.php]
```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;
```

Why it is not vulnerable: The user-controlled `$document_data['comment']` is passed through `htmlspecialchars()` with the `ENT_QUOTES` flag before being embedded in the HTML output. This encoding converts `<`, `>`, `&`, `"`, and `'` to their corresponding HTML entity equivalents, ensuring that any HTML or JavaScript content within the comment is rendered as plain text rather than being interpreted by the browser. The `nl2br()` function operates on the already-encoded string, so it cannot introduce injection vectors. The encoded text is safely wrapped in `<em>` tags for display.

Security invariants:
- User-supplied comment data must be HTML-encoded before embedding in HTML output — enforced by `htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset)`
- The `ENT_QUOTES` flag must be used to encode both single and double quotes — enforced by the explicit `ENT_QUOTES` argument in the `htmlspecialchars()` call
- The character encoding parameter `$charset` must match the actual document encoding for correct multi-byte character handling — the parameter is passed to `htmlspecialchars()` but its value is not visible in the supplied context
- The `nl2br()` transformation must not bypass or strip HTML encoding — enforced by `nl2br()` operating on the already-encoded output of `htmlspecialchars()`

Invariant verification:
- HTML entity encoding of user-controlled comment data: holds=true. Evidence: The call `htmlspecialchars($document_data['comment'], ENT_QUOTES, $charset)` encodes all HTML special characters before the comment is embedded in the output string
- Quote encoding to prevent attribute breakout: holds=true. Evidence: The `ENT_QUOTES` flag ensures both single quotes and double quotes are encoded, preventing attribute injection
- Safe ordering of encoding before transformation: holds=true. Evidence: `htmlspecialchars()` is applied first, then `nl2br()` operates on the encoded result, ensuring no unencoded content reaches the output

Residual risk notes: The `$charset` variable's value is not visible in the supplied context; if it does not match the actual document encoding, multi-byte characters may not be encoded correctly, potentially leading to encoding-related edge cases. Additionally, the source of `$document_data` and how `$document_data['comment']` is populated is not visible, though the output-time encoding provides defense-in-depth regardless of input sanitization.


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/torvalds/linux-2.6
Language: C
File: net/ceph/auth_x.c
Function: ceph_x_decrypt

Call path: ceph_x_handle_reply (net/ceph/auth_x.c) → ceph_x_proc_ticket_reply (net/ceph/auth_x.c) → process_one_ticket (net/ceph/auth_x.c) → ceph_x_decrypt (net/ceph/auth_x.c) → ceph_decode_copy (include/linux/ceph/decode.h)

### Primary Function

```c
static int ceph_x_decrypt(struct ceph_crypto_key *secret,
			  void **p, void *end, void *obuf, size_t olen)
{
	struct ceph_x_encrypt_header head;
	size_t head_len = sizeof(head);
	int len, ret;

	len = ceph_decode_32(p);
	if (*p + len > end)
		return -EINVAL;

	dout("ceph_x_decrypt len %d\n", len);
	ret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen,
			    *p, len);
	if (ret)
		return ret;
	if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)
		return -EPERM;
	*p += len;
	return olen;
}
```

### Cross-File Context

[TEMP_TICKET_BUF_LEN — macro — net/ceph/auth_x.c:16]
TEMP_TICKET_BUF_LEN → 256  (net/ceph/auth_x.c:16)

[CEPHX_ENC_MAGIC — constant — net/ceph/auth_x_protocol.h:83]
CEPHX_ENC_MAGIC → 0xff009cad8826aa55ull  (net/ceph/auth_x_protocol.h:83)

[ceph_x_encrypt_header — struct — net/ceph/auth_x_protocol.h:85-88]
```c
struct ceph_x_encrypt_header {\n\t__u8 struct_v;\n\t__le64 magic;\n} __attribute__ ((packed));
```

[ceph_decode_copy — sink — include/linux/ceph/decode.h:41-45]
ceph_decode_copy → static inline void ceph_decode_copy(void **p, void *pv, size_t n)\n{\n\tmemcpy(pv, *p, n);\n\t*p += n;\n}  (include/linux/ceph/decode.h:41-45)

[ceph_decode_32 — function — include/linux/ceph/decode.h:23-28]
```c
static inline u32 ceph_decode_32(void **p)\n{\n\tu32 v = get_unaligned_le32(*p);\n\t*p += sizeof(u32);\n\treturn v;\n}
```

[ceph_decode_8_safe — macro — include/linux/ceph/decode.h:76-80]
ceph_decode_8_safe → #define ceph_decode_8_safe(p, end, v, bad)\t \t\n\tdo {\t\t\t\t\t\t\t\t\t\n\t\tceph_decode_need(p, end, sizeof(u8), bad);\t\n\t\tv = ceph_decode_8(p);\t\t\t\t\n\t} while (0)  (include/linux/ceph/decode.h:76-80)

[ceph_decode_32_safe — macro — include/linux/ceph/decode.h:66-70]
ceph_decode_32_safe → #define ceph_decode_32_safe(p, end, v, bad)\t \t\n\tdo {\t\t\t\t\t\t\t\t\t\n\t\tceph_decode_need(p, end, sizeof(u32), bad);\t\n\t\tv = ceph_decode_32(p);\t\t\t\t\n\t} while (0)  (include/linux/ceph/decode.h:66-70)

[ceph_decode_need — macro — include/linux/ceph/decode.h:55-59]
ceph_decode_need → #define ceph_decode_need(p, end, n, bad)\t\t\t\n\tdo {\t\t\t\t\t\t\t\t\n\t\tif (!likely(ceph_has_room(p, end, n)))\t\t\n\t\t\tgoto bad;\t\t\t\t\t\n\t} while (0)  (include/linux/ceph/decode.h:55-59)

Control flow: ceph_x_handle_reply dispatches to ceph_x_proc_ticket_reply which iterates over ticket replies calling process_one_ticket for each. process_one_ticket calls ceph_x_decrypt to decrypt ticket data. The pre-fix code passes a fixed 256-byte buffer to ceph_x_decrypt which is insufficient for large tickets. ceph_decrypt2 internally calls ceph_decode_copy which performs the unbounded memcpy causing overflow.

Data flow: The ticket data originates from the Ceph Monitor in the network protocol. It is decoded from wire format via ceph_decode_32() to determine length 'dlen'. In the pre-fix code, this dlen value controls a memcpy into a 256-byte fixed buffer without validation against TEMP_TICKET_BUF_LEN. The attacker controls the ticket length in the protocol, enabling arbitrary overflow up to available memory.

Verdict: Vulnerable
Vulnerable region:
[net/ceph/auth_x.c]
```c
static int ceph_x_decrypt(struct ceph_crypto_key *secret,
			  void **p, void *end, void *obuf, size_t olen)
{
	struct ceph_x_encrypt_header head;
	size_t head_len = sizeof(head);
	int len, ret;

	len = ceph_decode_32(p);
	if (*p + len > end)
		return -EINVAL;

	dout("ceph_x_decrypt len %d\n", len);
	ret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen,
			    *p, len);
	if (ret)
		return ret;
	if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)
		return -EPERM;
	*p += len;
	return olen;
}
```
CWE: CWE-399
Severity: HIGH

Root cause: The TEMP_TICKET_BUF_LEN macro hardcodes a 256-byte buffer for cephx auth ticket decryption. The function ceph_x_decrypt receives obuf as a caller-allocated fixed-size buffer. When the actual encrypted/decrypted data length exceeds 256 bytes, ceph_decode_copy() in ceph_decrypt2 writes beyond the buffer boundary. This occurs in process_one_ticket when handling unencrypted tickets (is_enc=0) at line 213: ceph_decode_copy(p, ticket_buf, dlen) copies dlen bytes into ticket_buf which is allocated as TEMP_TICKET_BUF_LEN=256.

Exploitability: An attacker controlling a Ceph Monitor sends a crafted CEPHX auth ticket reply containing an unencrypted ticket blob with size > 256 bytes. The ceph_x_decrypt function uses a fixed 256-byte stack buffer, and the underlying ceph_decode_copy() performs an unbounded memcpy into this buffer, resulting in buffer overflow.

Attack preconditions:
- Attacker must control or compromise a Ceph Monitor to send crafted auth replies
- Target must be a Linux kernel Ceph client attempting authentication with the attacker-controlled monitor
- The crafted ticket must have is_enc=0 (unencrypted) with dlen > TEMP_TICKET_BUF_LEN (256 bytes)

Likely impact: An attacker controlling a Ceph Monitor sends a crafted CEPHX auth ticket reply containing an unencrypted ticket blob with size > 256 bytes. The ceph_x_decrypt function uses a fixed 256-byte stack buffer, and the underlying ceph_decode_copy() performs an unbounded memcpy into this buffer, resulting in buffer overflow.

Control flow: ceph_x_decrypt reads a 32-bit length from the input buffer via ceph_decode_32, validates the length against the buffer end using pointer arithmetic (*p + len > end), calls ceph_decrypt2 to decrypt the data into the output buffer, validates the decrypted header's struct_v and magic fields, then advances the input pointer by len and returns the output length. Error paths return -EINVAL for bounds violations, the return value from ceph_decrypt2 for decryption failures, and -EPERM for header validation failures.

Data flow: The input pointer *p is advanced by ceph_decode_32 to read len (u32). The len value is used in pointer arithmetic for bounds checking against end. The encrypted data at *p with size len is passed to ceph_decrypt2 along with the secret key. The decrypted header is validated for struct_v == 1 and magic == CEPHX_ENC_MAGIC. The output buffer obuf receives olen bytes of decrypted data. The input pointer *p is advanced by len after successful decryption.

Verdict: Not Vulnerable

Reviewed region:
[net/ceph/auth_x.c]
```c
static int ceph_x_decrypt(struct ceph_crypto_key *secret,
			  void **p, void *end, void *obuf, size_t olen)
{
	struct ceph_x_encrypt_header head;
	size_t head_len = sizeof(head);
	int len, ret;

	len = ceph_decode_32(p);
	if (*p + len > end)
		return -EINVAL;

	dout("ceph_x_decrypt len %d\n", len);
	ret = ceph_decrypt2(secret, &head, &head_len, obuf, &olen,
			    *p, len);
	if (ret)
		return ret;
	if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC)
		return -EPERM;
	*p += len;
	return olen;
}
```

Why it is not vulnerable: The bounds check `if (*p + len > end) return -EINVAL;` validates that the decrypted data region does not exceed the buffer boundary before ceph_decrypt2 processes it. While the pointer arithmetic `*p + len` could theoretically overflow on 32-bit systems with extreme len values (near SIZE_MAX), the len value is a u32 read from network data, and on 64-bit systems (the predominant deployment), pointer arithmetic with a u32 addition cannot wrap. The ceph_decrypt2 call receives the validated length and buffer pointer, and the header validation (struct_v == 1, magic == CEPHX_ENC_MAGIC) provides additional integrity verification of the decrypted content. The ceph_decode_copy sink in the call path is protected by the ceph_decode_need macro which checks ceph_has_room before allowing the memcpy to proceed.

Security invariants:
- The decrypted data length must not cause the input pointer to exceed the buffer end: enforced by `if (*p + len > end) return -EINVAL;` before ceph_decode2 is called
- The decrypted header must have valid magic and version fields: enforced by `if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC) return -EPERM;`
- The ceph_decrypt2 callee must not read beyond the validated len bytes: depends on ceph_decrypt2 implementation respecting the len parameter
- The ceph_decode_copy sink must validate buffer bounds before memcpy: enforced by ceph_decode_need macro checking ceph_has_room(p, end, n) before decoding

Invariant verification:
- Bounds validation before decryption: holds=true. Evidence: The check `if (*p + len > end) return -EINVAL;` is performed immediately after reading len and before calling ceph_decrypt2, ensuring the input pointer plus length does not exceed the buffer boundary
- Header integrity validation after decryption: holds=true. Evidence: The check `if (head.struct_v != 1 || le64_to_cpu(head.magic) != CEPHX_ENC_MAGIC) return -EPERM;` validates the decrypted header structure version and magic number match expected values
- Safe pointer arithmetic for bounds check: holds=true. Evidence: On 64-bit systems, `*p + len` where len is u32 cannot overflow a 64-bit pointer. On 32-bit systems, extreme len values near SIZE_MAX would be highly unusual in practice and the check still provides protection for typical input ranges
- Downstream ceph_decode_copy bounds safety: holds=true. Evidence: The ceph_decode_need macro checks `ceph_has_room(p, end, n)` before allowing ceph_decode_copy to perform memcpy, preventing buffer overread at the sink

Residual risk notes: The pointer arithmetic `*p + len` in the bounds check could theoretically overflow on 32-bit systems if len is crafted to be extremely large (near SIZE_MAX), potentially causing the bounds check to pass incorrectly. However, len is a u32 value from network data, and such extreme values would be highly anomalous. The ceph_decrypt2 implementation's internal bounds handling cannot be fully verified from the supplied context, though it receives a validated length parameter. The ceph_decode_copy sink relies on ceph_decode_need being called by its invoker (process_one_ticket), which is outside the current function's scope.