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/evmos/evmos
Language: Go
File: precompiles/vesting/tx.go
Function: FundVestingAccount

Call path: Precompile.Run (precompiles/vesting/vesting.go) → FundVestingAccount (precompiles/vesting/tx.go) → authorization.CheckAuthzExists (precompiles/authorization/authz.go) → vestingKeeper.FundVestingAccount (x/vesting/keeper/msg_server.go)

### Primary Function

```go
func (p *Precompile) FundVestingAccount(
	ctx sdk.Context,
	contract *vm.Contract,
	origin common.Address,
	stateDB vm.StateDB,
	method *abi.Method,
	args []interface{},
) ([]byte, error) {
	msg, funderAddr, vestingAddr, lockupPeriods, vestingPeriods, err := NewMsgFundVestingAccount(args, method)
	if err != nil {
		return nil, err
	}

	isContractCaller := contract.CallerAddress != origin

	// funder can only be the origin or the contract.Caller
	isContractFunder := contract.CallerAddress == funderAddr && isContractCaller

	if !isContractFunder && origin != funderAddr {
		return nil, fmt.Errorf(ErrDifferentFromOrigin, origin, funderAddr)
	}

	p.Logger(ctx).Debug(
		"tx called",
		"method", method.Name,
		"args", fmt.Sprintf(
			"{ from_address: %s, to_address: %s, start_time: %s, lockup_periods: %s, vesting_periods: %s }",
			msg.FunderAddress, msg.VestingAddress, msg.StartTime, msg.LockupPeriods, msg.VestingPeriods,
		),
	)

	// in case the contract is the funder
	// don't check for auth.
	// The smart contract (funder) should handle who is authorized to make this call
	if isContractCaller && !isContractFunder {
		// if calling from a contract and the contract is not the funder (origin == funderAddr)
		// check that an authorization exists
		_, _, err := authorization.CheckAuthzExists(ctx, p.AuthzKeeper, contract.CallerAddress, funderAddr, FundVestingAccountMsgURL)
		if err != nil {
			return nil, fmt.Errorf(authorization.ErrAuthzDoesNotExistOrExpired, FundVestingAccountMsgURL, contract.CallerAddress)
		}
	}

	_, err = p.vestingKeeper.FundVestingAccount(sdk.WrapSDKContext(ctx), msg)
	if err != nil {
		return nil, err
	}

	if isContractCaller {
		vestingCoins := msg.VestingPeriods.TotalAmount()
		lockedUpCoins := msg.LockupPeriods.TotalAmount()
		if vestingCoins.IsZero() && lockedUpCoins.IsAllPositive() {
			vestingCoins = lockedUpCoins
		}

		// NOTE: This ensures that the changes in the bank keeper are correctly mirrored to the EVM stateDB.
		amt := vestingCoins.AmountOf(utils.BaseDenom).BigInt()
		p.SetBalanceChangeEntries(
			cmn.NewBalanceChangeEntry(funderAddr, amt, cmn.Sub),
			cmn.NewBalanceChangeEntry(vestingAddr, amt, cmn.Add),
		)
	}

	if err = p.EmitFundVestingAccountEvent(ctx, stateDB, msg, funderAddr, vestingAddr, lockupPeriods, vestingPeriods); err != nil {
		return nil, err
	}

	return method.Outputs.Pack(true)
}
```

### Cross-File Context

[ErrDifferentFromOrigin — const — precompiles/vesting/errors.go:5]
ErrDifferentFromOrigin = "tx origin address %s does not match the from address %s"

[ErrDifferentFunderOrigin — const — precompiles/vesting/errors.go:7]
ErrDifferentFunderOrigin = "tx origin address %s does not match the funder address %s"

[CheckAuthzExists — function — precompiles/authorization/authz.go]
```go
func CheckAuthzExists(ctx sdk.Context, authzKeeper authzkeeper.Keeper, grantee, granter sdk.AccAddress, msgTypeURL string) (bool, time.Duration, error)
```

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 parses input arguments to extract transaction details and addresses. It evaluates whether the immediate caller is a smart contract (`isContractCaller`) and whether that contract is also the funding source (`isContractFunder`). It enforces that non-contract-funder calls must originate from the funder address. If a contract calls on behalf of another address, it validates explicit authorization via `CheckAuthzExists`. Upon successful validation, it invokes the vesting keeper, synchronizes EVM state balances for contract callers, emits a state transition event, and returns a success output.

Data flow: Input arguments are transformed into a `FundVestingAccountMsg` and relevant addresses via `NewMsgFundVestingAccount`. `origin` and `contract.CallerAddress` are compared to derive control flags. The `funderAddr` is strictly checked against `origin` for direct calls, or passed to `CheckAuthzExists` for indirect calls to verify grantee/granter relationships. The validated `msg` is passed to `vestingKeeper.FundVestingAccount`. Balance changes are derived from `msg.VestingPeriods` and `msg.LockupPeriods`, converted to big integers, and applied to the EVM `stateDB` via `SetBalanceChangeEntries` only when `isContractCaller` is true.

Verdict: Not Vulnerable

Reviewed region:
[precompiles/vesting/tx.go]
```go
func (p *Precompile) FundVestingAccount(
	ctx sdk.Context,
	contract *vm.Contract,
	origin common.Address,
	stateDB vm.StateDB,
	method *abi.Method,
	args []interface{},
) ([]byte, error) {
	msg, funderAddr, vestingAddr, lockupPeriods, vestingPeriods, err := NewMsgFundVestingAccount(args, method)
	if err != nil {
		return nil, err
	}

	isContractCaller := contract.CallerAddress != origin

	// funder can only be the origin or the contract.Caller
	isContractFunder := contract.CallerAddress == funderAddr && isContractCaller

	if !isContractFunder && origin != funderAddr {
		return nil, fmt.Errorf(ErrDifferentFromOrigin, origin, funderAddr)
	}

	p.Logger(ctx).Debug(
		"tx called",
		"method", method.Name,
		"args", fmt.Sprintf(
			"{ from_address: %s, to_address: %s, start_time: %s, lockup_periods: %s, vesting_periods: %s }",
			msg.FunderAddress, msg.VestingAddress, msg.StartTime, msg.LockupPeriods, msg.VestingPeriods,
		),
	)

	// in case the contract is the funder
	// don't check for auth.
	// The smart contract (funder) should handle who is authorized to make this call
	if isContractCaller && !isContractFunder {
		// if calling from a contract and the contract is not the funder (origin == funderAddr)
		// check that an authorization exists
		_, _, err := authorization.CheckAuthzExists(ctx, p.AuthzKeeper, contract.CallerAddress, funderAddr, FundVestingAccountMsgURL)
		if err != nil {
			return nil, fmt.Errorf(authorization.ErrAuthzDoesNotExistOrExpired, FundVestingAccountMsgURL, contract.CallerAddress)
		}
	}

	_, err = p.vestingKeeper.FundVestingAccount(sdk.WrapSDKContext(ctx), msg)
	if err != nil {
		return nil, err
	}

	if isContractCaller {
		vestingCoins := msg.VestingPeriods.TotalAmount()
		lockedUpCoins := msg.LockupPeriods.TotalAmount()
		if vestingCoins.IsZero() && lockedUpCoins.IsAllPositive() {
			vestingCoins = lockedUpCoins
		}

		// NOTE: This ensures that the changes in the bank keeper are correctly mirrored to the EVM stateDB.
		amt := vestingCoins.AmountOf(utils.BaseDenom).BigInt()
		p.SetBalanceChangeEntries(
			cmn.NewBalanceChangeEntry(funderAddr, amt, cmn.Sub),
			cmn.NewBalanceChangeEntry(vestingAddr, amt, cmn.Add),
		)
	}

	if err = p.EmitFundVestingAccountEvent(ctx, stateDB, msg, funderAddr, vestingAddr, lockupPeriods, vestingPeriods); err != nil {
		return nil, err
	}

	return method.Outputs.Pack(true)
}
```

Why it is not vulnerable: Authorization for the funder address is comprehensively enforced across all call paths. Direct user calls require `origin == funderAddr`. Indirect contract calls where the contract does not fund the transaction require explicit validation via `authorization.CheckAuthzExists`. Contracts funding themselves are exempt from user-level auth checks by design, as the contract governs its own funds. All validation gates execute before the state-modifying keeper call, preventing unauthorized state transitions.

Security invariants:
- Direct callers must match the funder address, enforced by `if !isContractFunder && origin != funderAddr` returning an error.
- Indirect callers acting on behalf of a user must possess valid authorization, enforced by the `if isContractCaller && !isContractFunder` block invoking `CheckAuthzExists`.
- Contract-to-contract funding bypasses user auth checks safely, as the calling contract (`contract.CallerAddress == funderAddr`) controls the funds, enforced by the `isContractFunder` flag.

Invariant verification:
- Authorization validation for indirect callers: holds=true. Evidence: The condition `isContractCaller && !isContractFunder` triggers `authorization.CheckAuthzExists(ctx, p.AuthzKeeper, contract.CallerAddress, funderAddr, FundVestingAccountMsgURL)`, which verifies that the calling contract holds a valid grant from the funder address before proceeding.
- Direct caller identity binding: holds=true. Evidence: The check `if !isContractFunder && origin != funderAddr` ensures that any non-contract-funder invocation must have the transaction origin exactly match the funder address, preventing unauthorized direct calls.
- Pre-condition enforcement before state mutation: holds=true. Evidence: All authorization and identity checks occur prior to `p.vestingKeeper.FundVestingAccount(...)`, ensuring no state changes are committed unless validation passes.

Residual risk notes: The logic relies on the correctness of `CheckAuthzExists` and the underlying authz module for grant expiration and scope validation. Additionally, `isContractCaller` assumes the EVM execution context accurately distinguishes between external users and contract boundaries, which is standard but depends on the runtime environment's address propagation.

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

Based on the provided code and cross-file context, there is no real vulnerability in this function. The implementation correctly establishes invariants to securely authenticate callers, validate authorizations, and synchronize EVM state.

### Analysis of the Guards and Invariants

1. **Funder Address Authorization & Integrity:**
   The function correctly limits who can act as the `funderAddr`. It enforces that the funder is strictly either:
   - The transaction's origin (the EOA that initiated the transaction).
   - The immediate contract caller (`contract.CallerAddress`), which means the contract is funding the vesting account from its own balance.

   This is safely guaranteed by:
   ```go
   isContractCaller := contract.CallerAddress != origin
   isContractFunder := contract.CallerAddress == funderAddr && isContractCaller

   if !isContractFunder && origin != funderAddr {
       return nil, fmt.Errorf(ErrDifferentFromOrigin, origin, funderAddr)
   }
   ```
   If the EOA is directly invoking the precompile (`isContractCaller == false`), it ensures `funderAddr == origin`.

2. **Implicit and Explicit Delegations (Authz):**
   If a smart contract acts as an intermediary (meaning `contract.CallerAddress != origin`) but attempts to use the EOA's funds (`funderAddr == origin`), the precompile explicitly enforces Cosmos-SDK `Authz` validation.
   ```go
   if isContractCaller && !isContractFunder {
       _, _, err := authorization.CheckAuthzExists(ctx, p.AuthzKeeper, contract.CallerAddress, funderAddr, FundVestingAccountMsgURL)
       // ...
   }
   ```
   This strictly prevents malicious intermediate contracts from unilaterally draining the origin user's balance to fund arbitrary vesting accounts, successfully thwarting "confused deputy" attacks.

3. **EVM State and Bank Keeper Synchronization:**
   Because `p.vestingKeeper.FundVestingAccount` modifies native Cosmos-SDK bank balances, the EVM state (`stateDB`) would typically desync. The implementation correctly calculates the base denomination (`utils.BaseDenom`) differences and applies manual journaled balance changes to the EVM state tree using `p.SetBalanceChangeEntries`. It appropriately catches edge cases where the core message sets `VestingPeriods` to zero but utilizes `LockupPeriods`.

### Conclusion
The relevant control flows properly validate permissions and synchronize EVM/Cosmos states. Intermediary execution paths are correctly insulated via Authz checks. Therefore, the analyzed code is not vulnerable.

```json
{
  "vulnerable": true,
  "cwe": "CWE-682",
  "severity": "High",
  "reviewed_region": "precompiles/vesting/tx.go",
  "vulnerable_region": "FundVestingAccount",
  "root_cause": "When synchronizing the EVM StateDB with the Cosmos Bank Keeper, the calculated transfer amount (`amt`) only considers `vestingCoins` if they are non-zero, completely ignoring `lockedUpCoins` if both are provided. If the underlying Cosmos module deducts based on a different calculation (e.g., locking up more coins than strictly vesting), the EVM state will fall out of sync with the true bank balance.",
  "exploitability": "An attacker can craft a transaction from a smart contract with a `MsgFundVestingAccount` containing a small `VestingPeriods` amount and a large `LockupPeriods` amount. The Cosmos bank keeper will process the full lockup, but the EVM state will only deduct the smaller vesting amount from the contract's EVM balance, allowing the contract to double-spend the difference.",
  "attack_preconditions": "The attacker must call the precompile from a smart contract and provide both `VestingPeriods` and `LockupPeriods` such that their total amounts differ.",
  "impact": "EVM StateDB and Cosmos SDK bank balances become desynchronized. An attacker can drain funds or double-spend tokens because the EVM balance is not decremented by the correct total amount transferred on the Cosmos side.",
  "non_vulnerable_reason": "",
  "security_invariants": [
    "The EVM state must be updated to exactly match the net balance changes applied by the Cosmos SDK keeper."
  ],
  "invariant_verification": "The logic `if vestingCoins.IsZero() && lockedUpCoins.IsAllPositive() { vestingCoins = lockedUpCoins }` attempts to determine the transferred amount but fails to correctly account for cases where both are non-zero but unequal, or where the true deducted amount is their sum or maximum.",
  "residual_risk_notes": "If the `MsgFundVestingAccount.ValidateBasic()` enforces that `VestingPeriods.TotalAmount()` always equals `LockupPeriods.TotalAmount()` when both are present, this specific desync might be unreachable. However, the precompile should reliably retrieve the actual amount deducted rather than guessing.",
  "call_path": "Precompile.Run -> FundVestingAccount -> vestingKeeper.FundVestingAccount"
}
```


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: https://github.com/torvalds/linux
Language: C
File: drivers/md/dm.c
Function: dm_submit_bio

Call path: do_preadv (fs/read_write.c) → vfs_iter_read (fs/read_write.c) → blkdev_read_iter (block/blk-core.c) → blkdev_direct_IO (block/blk-core.c) → __blkdev_direct_IO_simple (block/blk-dev.c) → submit_bio_noacct (block/blk-core.c) → dm_submit_bio (drivers/md/dm.c)

### Primary Function

```c
static void dm_submit_bio(struct bio *bio)
{
	struct mapped_device *md = bio->bi_bdev->bd_disk->private_data;
	int srcu_idx;
	struct dm_table *map;
	blk_opf_t bio_opf = bio->bi_opf;

	map = dm_get_live_table_bio(md, &srcu_idx, bio_opf);

	/* If suspended, or map not yet available, queue this IO for later */
	if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) ||
	    unlikely(!map)) {
		if (bio->bi_opf & REQ_NOWAIT)
			bio_wouldblock_error(bio);
		else if (bio->bi_opf & REQ_RAHEAD)
			bio_io_error(bio);
		else
			queue_io(md, bio);
		goto out;
	}

	dm_split_and_process_bio(md, map, bio);
out:
	dm_put_live_table_bio(md, srcu_idx, bio_opf);
}
```

### Cross-File Context

[dm_get_live_table_bio — function — drivers/md/dm.c:718-725]
```c
static inline struct dm_table *dm_get_live_table_bio(struct mapped_device *md,
					int *srcu_idx, blk_opf_t bio_opf)
{
	if (bio_opf & REQ_NOWAIT)
		return dm_get_live_table_fast(md);
	else
		return dm_get_live_table(md, srcu_idx);
}
```

[dm_put_live_table_bio — function — drivers/md/dm.c:727-734]
```c
static inline void dm_put_live_table_bio(struct mapped_device *md, int srcu_idx,
						 blk_opf_t bio_opf)
{
	if (bio_opf & REQ_NOWAIT)
		dm_put_live_table_fast(md);
	else
		dm_put_live_table(md, srcu_idx);
}
```

[dm_get_live_table_fast — function — drivers/md/dm.c:707-711]
```c
static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
{
	rcu_read_lock();
	return rcu_dereference(md->map);
}
```

[dm_put_live_table_fast — function — drivers/md/dm.c:713-716]
```c
static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
{
	rcu_read_unlock();
}
```

[dm_get_live_table — function — drivers/md/dm.c:683-689]
```c
struct dm_table *dm_get_live_table(struct mapped_device *md,
					   int *srcu_idx) __acquires(md->io_barrier)
{
	*srcu_idx = srcu_read_lock(&md->io_barrier);

	return srcu_dereference(md->map, &md->io_barrier);
}
```

[dm_put_live_table — function — drivers/md/dm.c:691-695]
```c
void dm_put_live_table(struct mapped_device *md,
			       int srcu_idx) __releases(md->io_barrier)
{
	srcu_read_unlock(&md->io_barrier, srcu_idx);
}
```

[REQ_NOWAIT — constant — include/linux/blk_types.h:451]
REQ_NOWAIT → (__force blk_opf_t)(1ULL << __REQ_NOWAIT)  (include/linux/blk_types.h:451)

[DMF_BLOCK_IO_FOR_SUSPEND — constant — drivers/md/dm-core.h:152]
DMF_BLOCK_IO_FOR_SUSPEND → 0  (drivers/md/dm-core.h:152)

[struct mapped_device — struct — drivers/md/dm-core.h:47-147]
```c
struct mapped_device {
	struct mutex suspend_lock;

	struct mutex table_devices_lock;
	struct list_head table_devices;

	/*
	 * The current mapping (struct dm_table *).
	 * Use dm_get_live_table{_fast} or take suspend_lock for
	 * dereference.
	 */
	void __rcu *map;

	unsigned long flags;

	/* Protect queue and type against concurrent access. */
	struct mutex type_lock;
	enum dm_queue_mode type;

	int numa_node_id;
	struct request_queue *queue;

	atomic_t holders;
	atomic_t open_count;

	struct dm_target *immutable_target;
	struct target_type *immutable_target_type;

	char name[16];
	struct gendisk *disk;
	struct dax_device *dax_dev;

	wait_queue_head_t wait;
	unsigned long __percpu *pending_io;

	/* forced geometry settings */
	struct hd_geometry geometry;

	/*
	 * Processing queue (flush)
	 */
	struct workqueue_struct *wq;

	/*
	 * A list of ios that arrived while we were suspended.
	 */
	struct work_struct work;
	spinlock_t deferred_lock;
	struct bio_list deferred;

	/*
	 * requeue work context is needed for cloning one new bio
	 * to represent the dm_io to be requeued, since each
	 * dm_io may point to the original bio from FS.
	 */
	struct work_struct requeue_work;
	struct dm_io *requeue_list;

	void *interface_ptr;

	/*
	 * Event handling.
	 */
	wait_queue_head_t eventq;
	atomic_t event_nr;
	atomic_t uevent_seq;
	struct list_head uevent_list;
	spinlock_t uevent_lock; /* Protect access to uevent_list */

	/* for blk-mq request-based DM support */
	bool init_tio_pdu:1;
	struct blk_mq_tag_set *tag_set;

	struct dm_stats stats;

	/* the number of internal suspends */
	unsigned int internal_suspend_count;

	int swap_bios;
	struct semaphore swap_bios_semaphore;
	struct mutex swap_bios_lock;

	/*
	 * io objects are allocated from here.
	 */
	struct dm_md_mempools *mempools;

	/* kobject and completion */
	struct dm_kobject_holder kobj_holder;

	struct srcu_struct io_barrier;

#ifdef CONFIG_BLK_DEV_ZONED
	unsigned int nr_zones;
	unsigned int *zwp_offset;
#endif

#ifdef CONFIG_IMA
	struct dm_ima_measurements ima;
#endif
};
```

Control flow: User issues preadv2 with RWF_NOWAIT on a device mapper device. The kernel traverses through do_preadv -> vfs_iter_read -> blkdev_read_iter -> blkdev_direct_IO -> submit_bio_noacct -> dm_submit_bio. In dm_submit_bio, the buggy code path selected the RCU-only fast path for REQ_NOWAIT bios and attempted to submit the bio under RCU protection, eventually calling mempool_alloc (which can sleep) via bio_alloc_clone, triggering the bug.

Data flow: The attacker-controlled input is the RWF_NOWAIT flag passed to preadv2, which sets bio->bi_opf & REQ_NOWAIT. This flag is checked in dm_get_live_table_bio to select the RCU-only fast path. The bio structure flows through dm_submit_bio -> dm_split_and_process_bio -> bio_alloc_clone -> mempool_alloc, where the sleeping assumption is violated.

Verdict: Vulnerable
Vulnerable region:
[drivers/md/dm.c]
```c
static void dm_submit_bio(struct bio *bio)
{
	struct mapped_device *md = bio->bi_bdev->bd_disk->private_data;
	int srcu_idx;
	struct dm_table *map;
	blk_opf_t bio_opf = bio->bi_opf;

	map = dm_get_live_table_bio(md, &srcu_idx, bio_opf);

	/* If suspended, or map not yet available, queue this IO for later */
	if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) ||
	    unlikely(!map)) {
		if (bio->bi_opf & REQ_NOWAIT)
			bio_wouldblock_error(bio);
		else if (bio->bi_opf & REQ_RAHEAD)
			bio_io_error(bio);
		else
			queue_io(md, bio);
		goto out;
	}

	dm_split_and_process_bio(md, map, bio);
out:
	dm_put_live_table_bio(md, srcu_idx, bio_opf);
}
```
CWE: CWE-667
Severity: MEDIUM

Root cause: The buggy helper functions dm_get_live_table_bio and dm_put_live_table_bio checked for REQ_NOWAIT and conditionally used the RCU-only fast path (dm_get_live_table_fast/dm_put_live_table_fast) instead of the SRCU-protected full table access. When a bio had REQ_NOWAIT set, the code path used RCU-only locking which does not prevent sleeping, but subsequent code (dm_split_and_process_bio -> bio_alloc_clone -> mempool_alloc with GFP_NOIO) required sleeping. REQ_NOWAIT only means 'do not wait for other IO', not 'this operation cannot sleep'.

Exploitability: An unprivileged user can trigger this bug by opening a device mapper device with O_DIRECT and issuing a preadv2 with RWF_NOWAIT flag, causing an immediate kernel panic or hang due to sleeping under RCU protection.

Attack preconditions:
- Attacker must have access to a device mapper device (/dev/dm-X)
- Attacker must be able to open the device with O_DIRECT flag
- Attacker must issue a read or write operation with RWF_NOWAIT flag

Likely impact: An unprivileged user can trigger this bug by opening a device mapper device with O_DIRECT and issuing a preadv2 with RWF_NOWAIT flag, causing an immediate kernel panic or hang due to sleeping under RCU protection.

Based on a careful review of the supplied code and cross-file context, the `dm_submit_bio` function does **not** present a vulnerability.

### Analysis
The most likely candidate for a vulnerability here would be a lock imbalance if the `bio` object's flags (`bio->bi_opf`) were modified during execution.

1. **Lock Acquisition:** `dm_get_live_table_bio(md, &srcu_idx, bio_opf)` conditionally acquires either an RCU read lock or an SRCU read lock based on the `REQ_NOWAIT` flag within the locally cached `bio_opf` variable.
2. **Execution:** The code branches into either an error path, queueing, or normal processing via `dm_split_and_process_bio(md, map, bio)`. Functions deep within the bio processing stack could potentially modify `bio->bi_opf` (for instance, clearing flags as the bio progresses).
3. **Lock Release:** `dm_put_live_table_bio(md, srcu_idx, bio_opf)` correctly releases the matching RCU or SRCU lock using the *cached* `bio_opf` variable, not the potentially modified `bio->bi_opf`.

Because the code explicitly caches `bio->bi_opf` at the start of the function and uses that local copy `bio_opf` to determine which lock type to acquire and subsequently release, it strictly guarantees lock/unlock pairing and avoids any imbalance. Furthermore, when `REQ_NOWAIT` is set (meaning we are holding a non-preemptible standard RCU read lock), the bio flags dictate that the subsequent I/O path must not sleep, adhering to RCU requirements. If `REQ_NOWAIT` is not set, the code holds an SRCU read lock, which safely allows sleeping.

Therefore, the implementation correctly maintains structural and concurrency invariants.

```json
{
  "vulnerable": false,
  "cwe": "N/A",
  "severity": "None",
  "reviewed_region": "static void dm_submit_bio(struct bio *bio)",
  "vulnerable_region": "N/A",
  "root_cause": "N/A",
  "exploitability": "N/A",
  "attack_preconditions": "N/A",
  "impact": "N/A",
  "non_vulnerable_reason": "The code safely caches bio->bi_opf into a local variable bio_opf at the beginning of the function. This ensures that the exact same flag state is evaluated during the lock acquisition in dm_get_live_table_bio and the lock release in dm_put_live_table_bio. Even if the underlying bio->bi_opf flags are modified during dm_split_and_process_bio, the RCU or SRCU lock types will remain perfectly balanced.",
  "security_invariants": [
    "Lock acquisition and release must rely on an immutable copy of the state (bio_opf) rather than a structure member that can be modified during processing (bio->bi_opf)."
  ],
  "invariant_verification": "The variable `bio_opf` is initialized as `blk_opf_t bio_opf = bio->bi_opf;` and passed by value to `dm_get_live_table_bio` and `dm_put_live_table_bio`, ensuring consistency.",
  "residual_risk_notes": "None based on the supplied context.",
  "call_path": "do_preadv -> vfs_iter_read -> blkdev_read_iter -> blkdev_direct_IO -> __blkdev_direct_IO_simple -> submit_bio_noacct -> dm_submit_bio"
}
```


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/anchore/syft
Language: Go
File: internal/config/attest.go
Function: attest

Call path: Packages (cmd/syft/cli/packages.go) → logApplicationConfig (cmd/syft/cli/commands.go) → Application.String (internal/config/application.go) → yaml.Marshal (builtin)

### Primary Function

```go
type attest struct {
	Key      string `yaml:"key" json:"key" mapstructure:"key"`
	Password string `yaml:"password" json:"password" mapstructure:"password"`
}
```

### Cross-File Context

[Application — struct — internal/config/application.go]
```go
type Application struct {
	// ... other fields ...
	Attest             attest             `yaml:"attest" json:"attest" mapstructure:"attest"`
	// ... other fields ...
}
```

[Application.String — callee — internal/config/application.go]
func (cfg Application) String() string { // yaml is pretty human friendly (at least when compared to json) appaStr, err := yaml.Marshal(&cfg) if err != nil { return err.Error() } return string(appaStr) }

[logApplicationConfig — caller — cmd/syft/cli/commands.go]
```go
func logApplicationConfig(app *config.Application) {
	versionInfo := version.FromBuild()
	log.Infof("%s version: %+v", internal.ApplicationName, versionInfo.Version)
	log.Debugf("application config:\n%+v", color.Magenta.Sprint(app.String()))
}
```

Control flow: When syft packages -vvv is executed, logApplicationConfig() is called which invokes app.String(). The String() method calls yaml.Marshal(&cfg) on the entire Application struct. Due to the json:"key" and json:"password" tags on the attest struct fields, the Key and Password values are included in the marshaled output, which is then logged via log.Debugf().

Data flow: Environment variables SYFT_ATTEST_PASSWORD and SYFT_ATTEST_KEY are loaded by viper into app.Attest.Password and app.Attest.Key respectively during app.LoadAllValues(). When logApplicationConfig() is called (enabled by -vvv flag), app.String() invokes yaml.Marshal(&cfg) which serializes the entire Application struct including the attest fields with non-omitted json tags, causing sensitive values to appear in the serialized output.

Verdict: Vulnerable
Vulnerable region:
[internal/config/attest.go]
```go
type attest struct {
```
CWE: CWE-200,CWE-532
Severity: MEDIUM

Root cause: The attest struct in internal/config/attest.go had json:"key" and json:"password" struct tags, causing the Key and Password field values to be included in JSON/YAML serialization when the Application config was marshaled. When syft packages -vvv -o json is run with SYFT_ATTEST_PASSWORD or SYFT_ATTEST_KEY environment variables set, the app.String() method calls yaml.Marshal(&cfg) which serializes the entire Application struct including the attest struct's sensitive fields, exposing them in debug output.

Exploitability: An attacker with the ability to set environment variables SYFT_ATTEST_PASSWORD or SYFT_ATTEST_KEY can cause these sensitive values to appear in debug output when running syft packages -vvv -o json, potentially exposing credentials in logs or CI/CD artifacts.

Attack preconditions:
- Attacker can set SYFT_ATTEST_PASSWORD and/or SYFT_ATTEST_KEY environment variables
- Victim runs syft packages command with -vvv (debug verbosity) and -o json output flags
- Application config is logged via logApplicationConfig() in cmd/syft/cli/commands.go

Likely impact: An attacker with the ability to set environment variables SYFT_ATTEST_PASSWORD or SYFT_ATTEST_KEY can cause these sensitive values to appear in debug output when running syft packages -vvv -o json, potentially exposing credentials in logs or CI/CD artifacts.

### Analysis

The candidate code defines an `attest` struct containing a `Password` field. This struct is embedded in the central `Application` configuration struct used by the application.

The `Application.String()` method is designed to serialize the entire application configuration into a human-readable YAML string using `yaml.Marshal(&cfg)`. Because the `Password` field lacks any redaction mechanisms (such as being omitted from the YAML tags or being masked via a custom `MarshalYAML` implementation), the plain text value of `Password` is included in the resulting serialized string.

In the call path, the `logApplicationConfig` function invokes `app.String()` and writes the output to the application's debug log: `log.Debugf("application config:\n%+v", color.Magenta.Sprint(app.String()))`.

As a result, if the application is executed with debug logging enabled, the attestation password will be written to the log files in plain text. This is a classic case of sensitive information exposure through log files.

### Verdict

**Vulnerable**

### Root Cause

The `attest` struct does not implement masking or redaction for its `Password` field. When the parent `Application` struct is marshaled into YAML for logging purposes, the sensitive `Password` field is serialized and subsequently dumped into the debug logs.

### Impact

An attacker with read access to the application's debug logs (e.g., in a CI/CD pipeline, centralized logging server, or local disk) can extract the attestation password. This could allow them to forge attestations or access associated signing keys.

### Vulnerability Classification

CWE-532: Insertion of Sensitive Information into Log File (Information Exposure)

```json
{
  "vulnerable": true,
  "cwe": "CWE-532",
  "severity": "Medium",
  "reviewed_region": "type attest struct {\n\tKey      string `yaml:\"key\" json:\"key\" mapstructure:\"key\"`\n\tPassword string `yaml:\"password\" json:\"password\" mapstructure:\"password\"`\n}",
  "vulnerable_region": "type attest struct {\n\tKey      string `yaml:\"key\" json:\"key\" mapstructure:\"key\"`\n\tPassword string `yaml:\"password\" json:\"password\" mapstructure:\"password\"`\n}",
  "root_cause": "The `attest` struct does not redact or omit the sensitive `Password` field during YAML marshaling. When the application configuration is logged via `Application.String()`, the plain-text password is included.",
  "exploitability": "Exploitable by anyone with read access to the application's debug logs.",
  "attack_preconditions": "The application must be run with debug logging enabled, and an attacker must have access to the resulting logs.",
  "impact": "Exposure of the attestation password, which could allow an attacker to forge attestations if they also have access to the signing key.",
  "non_vulnerable_reason": "",
  "security_invariants": "",
  "invariant_verification": "",
  "residual_risk_notes": "",
  "call_path": "Packages (cmd/syft/cli/packages.go) \u2192 logApplicationConfig (cmd/syft/cli/commands.go) \u2192 Application.String (internal/config/application.go) \u2192 yaml.Marshal (builtin)"
}
```


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

Repository: git.kernel.org/pub/scm/linux/kernel/git/stable/linux
Language: C
File: drivers/block/ublk_drv.c
Function: __ublk_complete_rq

Call path: bdev_open (block/fops.c) → read (fs/block_dev.c) → submit_bio (block/blk_core.c) → __ublk_complete_rq (drivers/block/ublk_drv.c) → blk_update_request (block/blk_core.c) → blk_mq_end_request (block/blk_mq.c) → fput (fs/file_table.c) → blkdev_release (block/fops.c)

### Primary Function

```c
static inline void __ublk_complete_rq(struct request *req, struct ublk_io *io,
				      bool need_map)
{
	unsigned int unmapped_bytes;
	blk_status_t res = BLK_STS_OK;
	bool requeue;

	/* failed read IO if nothing is read */
	if (!io->res && req_op(req) == REQ_OP_READ)
		io->res = -EIO;

	if (io->res < 0) {
		res = errno_to_blk_status(io->res);
		goto exit;
	}

	/*
	 * FLUSH, DISCARD or WRITE_ZEROES usually won't return bytes returned, so end them
	 * directly.
	 *
	 * Both the two needn't unmap.
	 */
	if (req_op(req) != REQ_OP_READ && req_op(req) != REQ_OP_WRITE &&
	    req_op(req) != REQ_OP_DRV_IN)
		goto exit;

	/* for READ request, writing data in iod->addr to rq buffers */
	unmapped_bytes = ublk_unmap_io(need_map, req, io);

	/*
	 * Extremely impossible since we got data filled in just before
	 *
	 * Re-read simply for this unlikely case.
	 */
	if (unlikely(unmapped_bytes < io->res))
		io->res = unmapped_bytes;

	/*
	 * Run bio->bi_end_io() with softirqs disabled. If the final fput
	 * happens off this path, then that will prevent ublk's blkdev_release()
	 * from being called on current's task work, see fput() implementation.
	 *
	 * Otherwise, ublk server may not provide forward progress in case of
	 * reading the partition table from bdev_open() with disk->open_mutex
	 * held, and causes dead lock as we could already be holding
	 * disk->open_mutex here.
	 *
	 * Preferably we would not be doing IO with a mutex held that is also
	 * used for release, but this work-around will suffice for now.
	 */
	local_bh_disable();
	requeue = blk_update_request(req, BLK_STS_OK, io->res);
	local_bh_enable();
	if (requeue)
		blk_mq_requeue_request(req, true);
	else if (likely(!blk_should_fake_timeout(req->q)))
		__blk_mq_end_request(req, BLK_STS_OK);

	return;
exit:
	ublk_end_request(req, res);
}
```

### Cross-File Context

[ublk_end_request — function — drivers/block/ublk_drv.c:1149-1154]
```c
static void ublk_end_request(struct request *req, blk_status_t error)
{
	local_bh_disable();
	blk_mq_end_request(req, error);
	local_bh_enable();
}
```

[__ublk_abort_rq — function — drivers/block/ublk_drv.c:1250-1258]
```c
static inline void __ublk_abort_rq(struct ublk_queue *ubq,
		struct request *rq)
{
	/* We cannot process this rq so just requeue it. */
	if (ublk_nosrv_dev_should_queue_io(ubq->dev))
		blk_mq_requeue_request(rq, false);
	else
		ublk_end_request(rq, BLK_STS_IOERR);
}
```

[__ublk_do_auto_buf_reg — function — drivers/block/ublk_drv.c:1288-1307]
```c
static enum auto_buf_reg_res
__ublk_do_auto_buf_reg(const struct ublk_queue *ubq, struct request *req,
		       struct ublk_io *io, struct io_uring_cmd *cmd,
		       unsigned int issue_flags)
{
	int ret;

	ret = io_buffer_register_bvec(cmd, req, ublk_io_release,
				      io->buf.auto_reg.index, issue_flags);
	if (ret) {
		if (io->buf.auto_reg.flags & UBLK_AUTO_BUF_REG_FALLBACK) {
			ublk_auto_buf_reg_fallback(ubq, req->tag);
			return AUTO_BUF_REG_FALLBACK;
		}
		ublk_end_request(req, BLK_STS_IOERR);
		return AUTO_BUF_REG_FAIL;
	}

	return AUTO_BUF_REG_OK;
}
```

[local_bh_disable — macro — include/linux/interrupt.h]
local_bh_disable → #define local_bh_disable() do { } while (0)  (include/linux/interrupt.h)

[local_bh_enable — macro — include/linux/interrupt.h]
local_bh_enable → #define local_bh_enable() do { } while (0)  (include/linux/interrupt.h)

[blk_update_request — callee — block/blk-core.c]
```c
blk_status_t blk_update_request(struct request *req, blk_status_t error, unsigned int nr_bytes)
```

[blk_mq_end_request — callee — block/blk-mq.c]
```c
void blk_mq_end_request(struct request *req, blk_status_t error)
```

Control flow: The function __ublk_complete_rq processes I/O request completion with multiple paths. First, it checks for failed read I/O (io->res == 0 with REQ_OP_READ), setting io->res to -EIO. Then if io->res < 0, it converts to blk_status_t and jumps to the exit path. Operations that are not READ, WRITE, or DRV_IN skip unmapping and jump to exit. For READ/WRITE/DRV_IN operations, ublk_unmap_io() is called to unmap buffers, and io->res is adjusted if unmapped_bytes < io->res. Then local_bh_disable() is called, followed by blk_update_request(), then local_bh_enable(). If requeue is true, blk_mq_requeue_request() is called; otherwise __blk_mq_end_request() is called. The exit path calls ublk_end_request() which wraps blk_mq_end_request() in local_bh_disable/enable.

Data flow: Input parameters req, io, and need_map flow through status checking (io->res), operation type filtering (req_op(req)), buffer unmapping via ublk_unmap_io(), and result passing to blk_update_request() or ublk_end_request(). The io->res field is conditionally set to -EIO for failed reads, converted to blk_status_t on error, and potentially adjusted downward after unmapping. The requeue return value from blk_update_request() determines whether the request is requeued or ended. All request completion functions (blk_update_request, blk_mq_end_request) are invoked within local_bh_disable/enable pairs.

Verdict: Not Vulnerable

Reviewed region:
[drivers/block/ublk_drv.c]
```c
static inline void __ublk_complete_rq(struct request *req, struct ublk_io *io,
				      bool need_map)
{
	unsigned int unmapped_bytes;
	blk_status_t res = BLK_STS_OK;
	bool requeue;

	/* failed read IO if nothing is read */
	if (!io->res && req_op(req) == REQ_OP_READ)
		io->res = -EIO;

	if (io->res < 0) {
		res = errno_to_blk_status(io->res);
		goto exit;
	}

	/*
	 * FLUSH, DISCARD or WRITE_ZEROES usually won't return bytes returned, so end them
	 * directly.
	 *
	 * Both the two needn't unmap.
	 */
	if (req_op(req) != REQ_OP_READ && req_op(req) != REQ_OP_WRITE &&
	    req_op(req) != REQ_OP_DRV_IN)
		goto exit;

	/* for READ request, writing data in iod->addr to rq buffers */
	unmapped_bytes = ublk_unmap_io(need_map, req, io);

	/*
	 * Extremely impossible since we got data filled in just before
	 *
	 * Re-read simply for this unlikely case.
	 */
	if (unlikely(unmapped_bytes < io->res))
		io->res = unmapped_bytes;

	/*
	 * Run bio->bi_end_io() with softirqs disabled. If the final fput
	 * happens off this path, then that will prevent ublk's blkdev_release()
	 * from being called on current's task work, see fput() implementation.
	 *
	 * Otherwise, ublk server may not provide forward progress in case of
	 * reading the partition table from bdev_open() with disk->open_mutex
	 * held, and causes dead lock as we could already be holding
	 * disk->open_mutex here.
	 *
	 * Preferably we would not be doing IO with a mutex held that is also
	 * used for release, but this work-around will suffice for now.
	 */
	local_bh_disable();
	requeue = blk_update_request(req, BLK_STS_OK, io->res);
	local_bh_enable();
	if (requeue)
		blk_mq_requeue_request(req, true);
	else if (likely(!blk_should_fake_timeout(req->q)))
		__blk_mq_end_request(req, BLK_STS_OK);

	return;
exit:
	ublk_end_request(req, res);
}
```

Why it is not vulnerable: The function correctly disables bottom halves before all I/O request completion operations that may trigger file descriptor release callbacks. In the success path (lines 46-48), blk_update_request() is wrapped by local_bh_disable()/local_bh_enable(). In the error path, ublk_end_request() (cross-file context) similarly wraps blk_mq_end_request() with local_bh_disable()/local_bh_enable(). This ensures that any bio completion callbacks executed during request processing run with softirqs disabled, preventing fput() from invoking blkdev_release() on the current task's work queue and avoiding deadlock when disk->open_mutex is held. Both completion paths are consistently protected.

Security invariants:
- Bottom halves must be disabled before calling blk_update_request() in the success path to prevent softirq-driven callback execution; enforced by local_bh_disable() at line 46 before blk_update_request() at line 47
- Bottom halves must be disabled before calling blk_mq_end_request() in the error path; enforced by local_bh_disable() in ublk_end_request() before blk_mq_end_request() in the cross-file context
- Bottom halves must be re-enabled after completion functions return to maintain proper interrupt state; enforced by local_bh_enable() at line 48 in success path and within ublk_end_request() in error path
- All code paths must reach a request completion function; enforced by the control flow: success path calls blk_update_request() then either blk_mq_requeue_request() or __blk_mq_end_request(), while the exit path calls ublk_end_request()
- Failed read I/O must be detected and handled before normal completion; enforced by checking !io->res && req_op(req) == REQ_OP_READ and setting io->res = -EIO at lines 15-16

Invariant verification:
- BH disabled before blk_update_request() in success path: holds=true. Evidence: local_bh_disable() at line 46 immediately precedes blk_update_request(req, BLK_STS_OK, io->res) at line 47, and local_bh_enable() at line 48 follows
- BH disabled before blk_mq_end_request() in error path: holds=true. Evidence: ublk_end_request() in cross-file context calls local_bh_disable() before blk_mq_end_request(req, error) and local_bh_enable() after
- Error path reaches completion with proper BH protection: holds=true. Evidence: The 'goto exit' statement at lines 24-26 leads to exit: label at line 52, which calls ublk_end_request(req, res) that provides BH protection
- Requeue path handled after BH-enabled completion: holds=true. Evidence: blk_update_request() returns requeue status at line 47, and if requeue is true at line 49, blk_mq_requeue_request(req, true) is called after local_bh_enable() at line 48
- Failed read detection prevents silent data loss: holds=true. Evidence: Lines 15-16 check !io->res && req_op(req) == REQ_OP_READ and set io->res = -EIO, which causes the subsequent io->res < 0 check to trigger the error path

Residual risk notes: The local_bh_disable/enable macros in the cross-file context are shown as no-op stubs, which may indicate a specific kernel configuration where BH disabling is handled differently (e.g., preemptible kernel configuration). This could be a kernel config concern rather than a vulnerability in this driver code, as the macros would expand to meaningful implementations in configurations where BH control is needed. The ublk_unmap_io() function is called without its definition visible; if it performs operations that could trigger callbacks, the BH protection after it would be relevant. However, based on the control flow, BH is disabled before the subsequent blk_update_request() call which is the actual completion trigger.

Based on the provided code and context, the candidate code is **not vulnerable** to the deadlock issue it appears to address.

### Analysis of the Suspected Issue

The underlying concern in this code involves a known deadlock scenario in the `ublk` driver when a partition table is read during `bdev_open()` while holding `disk->open_mutex`.

In the Linux kernel's block layer, completing a `bio` (via `bio->bi_end_io()`) can ultimately drop the final reference to a block device, triggering `fput()` and eventually `blkdev_release()`.
If `fput()` is triggered from a context where softirqs (Bottom Halves/BH) are enabled, the actual release execution might be deferred to task work. If the `ublk` server task is currently holding `disk->open_mutex` and waiting for forward progress, deferring `fput()` to its own task work queue creates a deadlock, because the task work cannot run while the task is blocked waiting for the I/O to complete.

### Concrete Guards in the Code

To prevent this deadlock, the code explicitly ensures that the `bio` completion executes in an environment that forces the final `fput` to be dispatched asynchronously rather than relying on the current task's work queue.

1. **Explicit BH Disabling (`local_bh_disable()`)**:
   In `__ublk_complete_rq()`, the `blk_update_request()` call (which processes the `bio` completions and triggers `bio->bi_end_io()`) is heavily guarded by `local_bh_disable()` and `local_bh_enable()`.
   ```c
   local_bh_disable();
   requeue = blk_update_request(req, BLK_STS_OK, io->res);
   local_bh_enable();
   ```
   By running `blk_update_request()` with softirqs disabled, the code guarantees that the nested `fput()` call will recognize it is not in a preemptible/standard process context. Consequently, `fput()` will schedule the file release via a workqueue (`delayed_fput()`) rather than appending it to the current task's work, which safely avoids the `disk->open_mutex` deadlock.

2. **Consistent Handling in Error Paths**:
   Requests that do not require mapping or return an error branch to `exit: ublk_end_request(req, res);`.
   As shown in the cross-file context, `ublk_end_request()` safely wraps the entire `blk_mq_end_request()` in the exact same guard:
   ```c
   static void ublk_end_request(struct request *req, blk_status_t error)
   {
       local_bh_disable();
       blk_mq_end_request(req, error);
       local_bh_enable();
   }
   ```

### Conclusion
The provided snippet actively mitigates the `fput()` task work deadlock by strategically disabling Bottom Halves across the functions responsible for completing block I/O requests. The execution flow cleanly handles both the successful multi-part completion path and the fast-fail path securely.

```json
{
  "vulnerable": false,
  "cwe": "CWE-833",
  "severity": "none",
  "reviewed_region": "drivers/block/ublk_drv.c: __ublk_complete_rq",
  "vulnerable_region": "None",
  "root_cause": "No vulnerability. The code correctly handles bio completion to avoid deadlocks involving fput() and task work by disabling softirqs.",
  "exploitability": "Not applicable.",
  "attack_preconditions": "Not applicable.",
  "impact": "Not applicable.",
  "non_vulnerable_reason": "The code explicitly disables bottom halves using `local_bh_disable()` before calling `blk_update_request()` and `blk_mq_end_request()`. This forces `fput()` to schedule file release via a workqueue (`delayed_fput()`) rather than appending it to the current task's work, which safely avoids the `disk->open_mutex` deadlock.",
  "security_invariants": [
    "Bottom halves must be disabled during `blk_update_request` and `blk_mq_end_request` to ensure `fput` does not run synchronously on the current task's work queue."
  ],
  "invariant_verification": "The code wraps `blk_update_request` with `local_bh_disable()` and `local_bh_enable()`. The `exit` path calls `ublk_end_request()`, which also wraps `blk_mq_end_request()` with `local_bh_disable()` and `local_bh_enable()`.",
  "residual_risk_notes": "None.",
  "call_path": "bdev_open (block/fops.c) \u2192 read (fs/block_dev.c) \u2192 submit_bio (block/blk_core.c) \u2192 __ublk_complete_rq (drivers/block/ublk_drv.c) \u2192 blk_update_request (block/blk_core.c) \u2192 blk_mq_end_request (block/blk_mq.c) \u2192 fput (fs/file_table.c) \u2192 blkdev_release (block/fops.c)"
}
```


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

Repository: git.kernel.org/pub/scm/linux/kernel/git/stable/linux
Language: C
File: fs/nfsd/nfs2acl.c
Function: nfsacld_proc_getacl

Call path: nfsacld_proc_getacl (fs/nfsd/nfs2acl.c) → get_inode_acl (fs/nfsd/nfs2acl.c) → posix_acl_from_mode (fs/nfsd/nfs2acl.c) → posix_acl_release (fs/nfsd/nfs2acl.c) → nfsaclsvc_release_getacl (fs/nfsd/nfs2acl.c)

### Primary Function

```c
static __be32 nfsacld_proc_getacl(struct svc_rqst *rqstp)
{
	struct nfsd3_getaclargs *argp = rqstp->rq_argp;
	struct nfsd3_getaclres *resp = rqstp->rq_resp;
	struct posix_acl *acl;
	struct inode *inode;
	svc_fh *fh;

	dprintk("nfsd: GETACL(2acl)   %s\n", SVCFH_fmt(&argp->fh));

	fh = fh_copy(&resp->fh, &argp->fh);
	resp->status = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_NOP);
	if (resp->status != nfs_ok)
		goto out;

	inode = d_inode(fh->fh_dentry);

	if (argp->mask & ~NFS_ACL_MASK) {
		resp->status = nfserr_inval;
		goto out;
	}
	resp->mask = argp->mask;

	resp->status = fh_getattr(fh, &resp->stat);
	if (resp->status != nfs_ok)
		goto out;

	if (resp->mask & (NFS_ACL|NFS_ACLCNT)) {
		acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
		if (acl == NULL) {
			/* Solaris returns the inode's minimum ACL. */
			acl = posix_acl_from_mode(inode->i_mode, GFP_KERNEL);
		}
		if (IS_ERR(acl)) {
			resp->status = nfserrno(PTR_ERR(acl));
			goto fail;
		}
		resp->acl_access = acl;
	}
	if (resp->mask & (NFS_DFACL|NFS_DFACLCNT)) {
		/* Check how Solaris handles requests for the Default ACL
		   of a non-directory! */
		acl = get_inode_acl(inode, ACL_TYPE_DEFAULT);
		if (IS_ERR(acl)) {
			resp->status = nfserrno(PTR_ERR(acl));
			goto fail;
		}
		resp->acl_default = acl;
	}

	/* resp->acl_{access,default} are released in nfssvc_release_getacl. */
out:
	return rpc_success;

fail:
	posix_acl_release(resp->acl_access);
	posix_acl_release(resp->acl_default);
	goto out;
}
```

### Cross-File Context

[nfsaclsvc_release_getacl — sink — fs/nfsd/nfs2acl.c:297-304]
```c
static void nfsaclsvc_release_getacl(struct svc_rqst *rqstp)
{
	struct nfsd3_getaclres *resp = rqstp->rq_resp;

	fh_put(&resp->fh);
	posix_acl_release(resp->acl_access);
	posix_acl_release(resp->acl_default);
}
```

[nfsd3_proc_getacl — function — fs/nfsd/nfs3acl.c:28-76]
```c
static __be32 nfsd3_proc_getacl(struct svc_rqst *rqstp)
{
	struct nfsd3_getaclargs *argp = rqstp->rq_argp;
	struct nfsd3_getaclres *resp = rqstp->rq_resp;
	struct posix_acl *acl;
	struct inode *inode;
	svc_fh *fh;

	fh = fh_copy(&resp->fh, &argp->fh);
	resp->status = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_NOP);
	if (resp->status != nfs_ok)
		goto out;

	inode = d_inode(fh->fh_dentry);

	if (argp->mask & ~NFS_ACL_MASK) {
		resp->status = nfserr_inval;
		goto out;
	}
	resp->mask = argp->mask;

	if (resp->mask & (NFS_ACL|NFS_ACLCNT)) {
		acl = get_inode_acl(inode, ACL_TYPE_ACCESS);
		if (acl == NULL) {
			/* Solaris returns the inode's minimum ACL. */
			acl = posix_acl_from_mode(inode->i_mode, GFP_KERNEL);
		}
		if (IS_ERR(acl)) {
			resp->status = nfserrno(PTR_ERR(acl));
			goto fail;
		}
		resp->acl_access = acl;
	}
	if (resp->mask & (NFS_DFACL|NFS_DFACLCNT)) {
		/* Check how Solaris handles requests for the Default ACL
		   of a non-directory! */
		acl = get_inode_acl(inode, ACL_TYPE_DEFAULT);
		if (IS_ERR(acl)) {
			resp->status = nfserrno(PTR_ERR(acl));
			goto fail;
		}
		resp->acl_default = acl;
	}

	/* resp->acl_{access,default} are released in nfs3svc_release_getacl. */
out:
	return rpc_success;

fail:
	posix_acl_release(resp->acl_access);
	posix_acl_release(resp->acl_default);
	goto out;
}
```

[nfs3svc_release_getacl — function — fs/nfsd/nfs3acl.c:217-224]
```c
static void nfs3svc_release_getacl(struct svc_rqst *rqstp)
{
	struct nfsd3_getaclres *resp = rqstp->rq_resp;

	fh_put(&resp->fh);
	posix_acl_release(resp->acl_access);
	posix_acl_release(resp->acl_default);
}
```

[posix_acl_release — callee — include/linux/posix_acl.h:55-59]
```c
static inline void posix_acl_release(struct posix_acl *acl)
{
	if (acl && refcount_dec_and_test(&acl->a_refcount))
		kfree_rcu(acl, a_rcu);
}
```

[struct nfsd3_getaclres — struct — fs/nfsd/xdr3.h:222-229]
```c
struct nfsd3_getaclres {
	__be32			status;
	struct svc_fh		fh;
	int			mask;
	struct posix_acl	*acl_access;
	struct posix_acl	*acl_default;
	struct kstat		stat;
};
```

[NFS_ACL — constant — include/linux/nfsacl.h]
NFS_ACL → 1  (include/linux/nfsacl.h)

[NFS_DFACL — constant — include/linux/nfsacl.h]
NFS_DFACL → 2  (include/linux/nfsacl.h)

[NFS_ACL_MASK — constant — include/linux/nfsacl.h]
NFS_ACL_MASK → (NFS_ACL | NFS_ACLCNT | NFS_DFACL | NFS_DFACLCNT)  (include/linux/nfsacl.h)

Control flow: nfsacld_proc_getacl processes a GETACL request. It retrieves access ACL successfully, stores in resp->acl_access. It then attempts to retrieve default ACL, which fails and jumps to fail label. At fail label, it releases both ACLs via posix_acl_release without NULLing the pointers. Function returns error. Later, svc infrastructure calls nfsaclsvc_release_getacl which again releases the same already-freed ACLs, causing UAF.

Data flow: resp->acl_access and resp->acl_default are set from get_inode_acl results. On failure in the default ACL path, both are passed to posix_acl_release (freeing the underlying objects) but the pointers remain non-NULL. Later nfsaclsvc_release_getacl reads the same non-NULL pointers and passes them to posix_acl_release again.

Verdict: Vulnerable
Vulnerable region:
[fs/nfsd/nfs2acl.c]
```c
}
		resp->acl_default = acl;
	}

	/* resp->acl_{access,default} are released in nfssvc_release_getacl. */
```
CWE: CWE-416
Severity: HIGH

Root cause: When nfsacld_proc_getacl fails to get the default ACL (acl_default), it jumps to the fail label and releases both acl_access and acl_default via posix_acl_release. However, the response structure's acl_access and acl_default pointers are not set to NULL after releasing. When nfsaclsvc_release_getacl is later invoked (during svc response cleanup), it calls posix_acl_release again on the stale pointers pointing to the already-freed ACL objects, causing a use-after-free vulnerability.

Exploitability: An NFS client can trigger this by requesting both NFS_ACL and NFS_DFACL masks. If getting the default ACL fails (e.g., on a non-directory), the ACLs are released but pointers remain, and later svc release triggers double-free.

Attack preconditions:
- NFS server must be running with nfsd
- Client must have access to mount an NFS share
- Client must issue a GETACL request with mask requesting both access ACL (NFS_ACL) and default ACL (NFS_DFACL)
- The target inode's default ACL retrieval must fail (e.g., non-directory inode)

Likely impact: An NFS client can trigger this by requesting both NFS_ACL and NFS_DFACL masks. If getting the default ACL fails (e.g., on a non-directory), the ACLs are released but pointers remain, and later svc release triggers double-free.

An analysis of the provided code reveals a **double-free / Use-After-Free (UAF)** vulnerability.

### Vulnerability Analysis

In `nfsacld_proc_getacl`, the function is responsible for retrieving both the access ACL and the default ACL for an inode.

1. **First ACL Retrieval**:
   When the client requests an access ACL (`resp->mask & (NFS_ACL|NFS_ACLCNT)`), the function retrieves it, checks for errors, and assigns it:
   ```c
   resp->acl_access = acl;
   ```
2. **Second ACL Retrieval & Failure**:
   If the client also requests a default ACL (`resp->mask & (NFS_DFACL|NFS_DFACLCNT)`), the function attempts to retrieve it. If this retrieval fails (`IS_ERR(acl)`), execution jumps to the `fail` label:
   ```c
   if (IS_ERR(acl)) {
       resp->status = nfserrno(PTR_ERR(acl));
       goto fail;
   }
   ```
3. **The First Free**:
   At the `fail` label, the function releases the previously acquired access ACL:
   ```c
   fail:
       posix_acl_release(resp->acl_access);
       posix_acl_release(resp->acl_default);
       goto out;
   ```
   Crucially, this block does **not** set `resp->acl_access` to `NULL` after releasing it. The pointer remains intact.

4. **The Second Free (Double Free)**:
   The function then exits and yields control back to the RPC layer. When the RPC framework cleans up the request, it invokes the procedure's designated release function—`nfsaclsvc_release_getacl`.
   ```c
   static void nfsaclsvc_release_getacl(struct svc_rqst *rqstp)
   {
       struct nfsd3_getaclres *resp = rqstp->rq_resp;
       fh_put(&resp->fh);
       posix_acl_release(resp->acl_access);    // <--- Double Free!
       posix_acl_release(resp->acl_default);
   }
   ```
   Because `resp->acl_access` still holds the stale address, `posix_acl_release` is called again on the same object. This drops the reference count a second time (`refcount_dec_and_test`), leading to a Use-After-Free and a double free.

### Impact and Preconditions

**Exploitability:** The vulnerability is triggerable by a remote authenticated (or unauthenticated depending on the NFS export rules) client. The client simply needs to issue a `GETACL` request with a mask specifying both `NFS_ACL` and `NFS_DFACL`. If the server successfully resolves the access ACL but fails to get the default ACL (e.g., due to file system permission constraints or lack of support for default ACLs on the requested file), the error path is taken, triggering the double free.

**Impact:** A remote attacker can corrupt kernel memory by decrementing a freed object's reference count. This leads to heap corruption, kernel panics (Denial of Service), and potentially remote kernel code execution.

*(Note: The exact same vulnerability pattern is visible in `nfsd3_proc_getacl` in the provided cross-file context).*

```json
{
  "vulnerable": true,
  "cwe": "CWE-415",
  "severity": "High",
  "reviewed_region": "static __be32 nfsacld_proc_getacl(struct svc_rqst *rqstp)\n{\n\tstruct nfsd3_getaclargs *argp = rqstp->rq_argp;\n\tstruct nfsd3_getaclres *resp = rqstp->rq_resp;\n\tstruct posix_acl *acl;\n\tstruct inode *inode;\n\tsvc_fh *fh;\n\n\tdprintk(\"nfsd: GETACL(2acl)   %s\\n\", SVCFH_fmt(&argp->fh));\n\n\tfh = fh_copy(&resp->fh, &argp->fh);\n\tresp->status = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_NOP);\n\tif (resp->status != nfs_ok)\n\t\tgoto out;\n\n\tinode = d_inode(fh->fh_dentry);\n\n\tif (argp->mask & ~NFS_ACL_MASK) {\n\t\tresp->status = nfserr_inval;\n\t\tgoto out;\n\t}\n\tresp->mask = argp->mask;\n\n\tresp->status = fh_getattr(fh, &resp->stat);\n\tif (resp->status != nfs_ok)\n\t\tgoto out;\n\n\tif (resp->mask & (NFS_ACL|NFS_ACLCNT)) {\n\t\tacl = get_inode_acl(inode, ACL_TYPE_ACCESS);\n\t\tif (acl == NULL) {\n\t\t\t/* Solaris returns the inode's minimum ACL. */\n\t\t\tacl = posix_acl_from_mode(inode->i_mode, GFP_KERNEL);\n\t\t}\n\t\tif (IS_ERR(acl)) {\n\t\t\tresp->status = nfserrno(PTR_ERR(acl));\n\t\t\tgoto fail;\n\t\t}\n\t\tresp->acl_access = acl;\n\t}\n\tif (resp->mask & (NFS_DFACL|NFS_DFACLCNT)) {\n\t\t/* Check how Solaris handles requests for the Default ACL\n\t\t   of a non-directory! */\n\t\tacl = get_inode_acl(inode, ACL_TYPE_DEFAULT);\n\t\tif (IS_ERR(acl)) {\n\t\t\tresp->status = nfserrno(PTR_ERR(acl));\n\t\t\tgoto fail;\n\t\t}\n\t\tresp->acl_default = acl;\n\t}\n\n\t/* resp->acl_{access,default} are released in nfssvc_release_getacl. */\nout:\n\treturn rpc_success;\n\nfail:\n\tposix_acl_release(resp->acl_access);\n\tposix_acl_release(resp->acl_default);\n\tgoto out;\n}",
  "vulnerable_region": "fail:\n\tposix_acl_release(resp->acl_access);\n\tposix_acl_release(resp->acl_default);\n\tgoto out;",
  "root_cause": "The error path releases the ACL objects but fails to clear the pointers in the response structure (`resp->acl_access` and `resp->acl_default`). Later, the RPC cleanup routine `nfsaclsvc_release_getacl` unconditionally releases these pointers again, resulting in a double decrement of their reference count (Double Free / Use-After-Free).",
  "exploitability": "Likely. An attacker capable of interacting with the NFS server can request both access and default ACLs on an object. If the retrieval of the access ACL succeeds but the default ACL fails (which can be intentionally induced depending on directory settings), the error path is triggered. The pointer is released twice, leading to reference count underflow and a double free.",
  "attack_preconditions": "The attacker needs network access to the NFS server, sufficient permissions to send a GETACL request, and a file/directory configuration that succeeds for access ACL retrieval but fails for default ACL retrieval (e.g., requesting a default ACL on a non-directory or where it is unsupported).",
  "impact": "Double free and heap corruption, leading to Denial of Service (kernel crash) or potential privilege escalation/Remote Code Execution.",
  "non_vulnerable_reason": "",
  "security_invariants": "",
  "invariant_verification": "",
  "residual_risk_notes": "",
  "call_path": "nfsacld_proc_getacl (fs/nfsd/nfs2acl.c) \u2192 get_inode_acl (fs/nfsd/nfs2acl.c) \u2192 posix_acl_from_mode (fs/nfsd/nfs2acl.c) \u2192 posix_acl_release (fs/nfsd/nfs2acl.c) \u2192 nfsaclsvc_release_getacl (fs/nfsd/nfs2acl.c)"
}
```


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: https://github.com/torvalds/linux
Language: C
File: net/mptcp/subflow.c
Function: subflow_syn_recv_sock

Call path: tcp_v4_rcv (net/ipv4/tcp_ipv4.c) → tcp_check_req (net/ipv4/tcp_minisocks.c) → subflow_syn_recv_sock (net/mptcp/subflow.c) → mptcp_can_accept_new_subflow (net/mptcp/subflow.c)

### Primary Function

```c
static struct sock *subflow_syn_recv_sock(const struct sock *sk,
					  struct sk_buff *skb,
					  struct request_sock *req,
					  struct dst_entry *dst,
					  struct request_sock *req_unhash,
					  bool *own_req)
{
	struct mptcp_subflow_context *listener = mptcp_subflow_ctx(sk);
	struct mptcp_subflow_request_sock *subflow_req;
	struct mptcp_options_received mp_opt;
	bool fallback, fallback_is_fatal;
	struct sock *new_msk = NULL;
	struct sock *child;

	pr_debug("listener=%p, req=%p, conn=%p\n", listener, req, listener->conn);

	/* After child creation we must look for MPC even when options
	 * are not parsed
	 */
	mp_opt.suboptions = 0;

	/* hopefully temporary handling for MP_JOIN+syncookie */
	subflow_req = mptcp_subflow_rsk(req);
	fallback_is_fatal = tcp_rsk(req)->is_mptcp && subflow_req->mp_join;
	fallback = !tcp_rsk(req)->is_mptcp;
	if (fallback)
		goto create_child;

	/* if the sk is MP_CAPABLE, we try to fetch the client key */
	if (subflow_req->mp_capable) {
		/* we can receive and accept an in-window, out-of-order pkt,
		 * which may not carry the MP_CAPABLE opt even on mptcp enabled
		 * paths: always try to extract the peer key, and fallback
		 * for packets missing it.
		 * Even OoO DSS packets coming legitly after dropped or
		 * reordered MPC will cause fallback, but we don't have other
		 * options.
		 */
		mptcp_get_options(skb, &mp_opt);
		if (!(mp_opt.suboptions & OPTIONS_MPTCP_MPC)) {
			fallback = true;
			goto create_child;
		}

		new_msk = mptcp_sk_clone(listener->conn, &mp_opt, req);
		if (!new_msk)
			fallback = true;
	} else if (subflow_req->mp_join) {
		mptcp_get_options(skb, &mp_opt);
		if (!(mp_opt.suboptions & OPTION_MPTCP_MPJ_ACK))
			fallback = true;
	}

create_child:
	child = listener->icsk_af_ops->syn_recv_sock(sk, skb, req, dst,
						     req_unhash, own_req);

	if (child && *own_req) {
		struct mptcp_subflow_context *ctx = mptcp_subflow_ctx(child);

		tcp_rsk(req)->drop_req = false;

		/* we need to fallback on ctx allocation failure and on pre-reqs
		 * checking above. In the latter scenario we additionally need
		 * to reset the context to non MPTCP status.
		 */
		if (!ctx || fallback) {
			if (fallback_is_fatal) {
				subflow_add_reset_reason(skb, MPTCP_RST_EMPTCP);
				goto dispose_child;
			}

			if (fallback)
				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MPCAPABLEPASSIVEFALLBACK);

			subflow_drop_ctx(child);
			goto out;
		}

		/* ssk inherits options of listener sk */
		ctx->setsockopt_seq = listener->setsockopt_seq;

		if (ctx->mp_capable) {
			/* this can't race with mptcp_close(), as the msk is
			 * not yet exposted to user-space
			 */
			inet_sk_state_store((void *)new_msk, TCP_ESTABLISHED);

			/* record the newly created socket as the first msk
			 * subflow, but don't link it yet into conn_list
			 */
			WRITE_ONCE(mptcp_sk(new_msk)->first, child);

			/* new mpc subflow takes ownership of the newly
			 * created mptcp socket
			 */
			new_msk->sk_destruct = mptcp_sock_destruct;
			mptcp_sk(new_msk)->setsockopt_seq = ctx->setsockopt_seq;
			mptcp_pm_new_connection(mptcp_sk(new_msk), child, 1);
			mptcp_token_accept(subflow_req, mptcp_sk(new_msk));
			ctx->conn = new_msk;
			new_msk = NULL;

			/* with OoO packets we can reach here without ingress
			 * mpc option
			 */
			if (mp_opt.suboptions & OPTIONS_MPTCP_MPC)
				mptcp_subflow_fully_established(ctx, &mp_opt);
		} else if (ctx->mp_join) {
			struct mptcp_sock *owner;

			owner = subflow_req->msk;
			if (!owner) {
				subflow_add_reset_reason(skb, MPTCP_RST_EPROHIBIT);
				goto dispose_child;
			}

			if (!subflow_hmac_valid(req, &mp_opt) ||
			    !mptcp_can_accept_new_subflow(subflow_req->msk)) {
				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINACKMAC);
				subflow_add_reset_reason(skb, MPTCP_RST_EPROHIBIT);
				goto dispose_child;
			}

			/* move the msk reference ownership to the subflow */
			subflow_req->msk = NULL;
			ctx->conn = (struct sock *)owner;

			if (subflow_use_different_sport(owner, sk)) {
				pr_debug("ack inet_sport=%d %d\n",
					 ntohs(inet_sk(sk)->inet_sport),
					 ntohs(inet_sk((struct sock *)owner)->inet_sport));
				if (!mptcp_pm_sport_in_anno_list(owner, sk)) {
					SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MISMATCHPORTACKRX);
					goto dispose_child;
				}
				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINPORTACKRX);
			}

			if (!mptcp_finish_join(child))
				goto dispose_child;

			SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINACKRX);
			tcp_rsk(req)->drop_req = true;
		}
	}

out:
	/* dispose of the left over mptcp master, if any */
	if (unlikely(new_msk))
		mptcp_force_close(new_msk);

	/* check for expected invariant - should never trigger, just help
	 * catching eariler subtle bugs
	 */
	if (ctx && ctx->mp_join && ctx->conn)
		 WARN_ON_ONCE(ctx->conn != (struct sock *)subflow_req->msk);

	return child;

dispose_child:
	tcp_rsk(req)->drop_req = true;
	if (child)
		tcp_close(child, 0);
	return NULL;
}
```

### Cross-File Context

[mptcp_can_accept_new_subflow — sink — net/mptcp/subflow.c:64]
```c
static bool mptcp_can_accept_new_subflow(const struct mptcp_sock *msk)
{
	return mptcp_is_fully_established((void *)msk) &&
	       READ_ONCE(msk->pm.accept_subflow);
}
```

[subflow_hmac_valid — function — net/mptcp/subflow.c:583]
```c
static bool subflow_hmac_valid(const struct request_sock *req,
				       const struct mptcp_options_received *mp_opt)
{
	const struct mptcp_subflow_request_sock *subflow_req;
	u8 hmac[SHA256_DIGEST_SIZE];
	struct mptcp_sock *msk;

	subflow_req = mptcp_subflow_rsk(req);
	msk = subflow_req->msk;

	subflow_generate_hmac(msk->remote_key, msk->local_key,
			      subflow_req->remote_nonce,
			      subflow_req->local_nonce, hmac);

	return !crypto_memneq(hmac, mp_opt->hmac, MPTCPOPT_HMAC_LEN);
}
```

[mptcp_subflow_request_sock — struct — include/net/mptcp.h]
```c
struct mptcp_subflow_request_sock {
	struct request_sock sk;
	unsigned int msk_accessed:1;
	unsigned int mp_capable:1;
	unsigned int mp_join:1;
	unsigned int csum_reqd:1;
	unsigned int allow_join_id0:1;
	unsigned int request_bkup:1;
	u32 remote_nonce;
	u32 local_nonce;
	u64 thmac;
	u32 token;
	u16 remote_id;
	u8 local_id;
	struct mptcp_sock *msk;
};
```

[SUBFLOW_REQ_INC_STATS — macro — net/mptcp/subflow.c:28]
SUBFLOW_REQ_INC_STATS → #define SUBFLOW_REQ_INC_STATS(req, field) \ MPTCP_INC_STATS(sock_net(req_to_sk(req)), field)  (net/mptcp/subflow.c:28)

[subflow_add_reset_reason — function — net/mptcp/subflow.c:118]
```c
static void subflow_add_reset_reason(struct sk_buff *skb, u8 reason)
{
	struct mptcp_ext *mpext = skb_ext_add(skb, SKB_EXT_MPTCP);

	if (mpext) {
		memset(mpext, 0, sizeof(*mpext));
		mpext->reset_reason = reason;
	}
}
```

Control flow: The function processes MP-TCP SYN-ACK for either a new MP_CAPABLE connection or an MP_JOIN subflow. Path 1 (MP_CAPABLE): extracts MPC options from skb, clones a new msk via mptcp_sk_clone(), then delegates to the transport's syn_recv_sock(). If the cloned msk fails or MPC option is missing, it falls back to standard TCP. After child creation, if ctx and !fallback, it links the new msk to the subflow and calls mptcp_pm_new_connection() and mptcp_token_accept(). Path 2 (MP_JOIN): validates HMAC and checks mptcp_can_accept_new_subflow(), verifies the owner msk exists, optionally checks source port annotation list, then calls mptcp_finish_join(). Error paths via 'dispose_child' set drop_req=true, close the child socket, and return NULL. Cleanup at 'out' disposes any leftover new_msk.

Data flow: Inputs include the listener socket (sk), incoming skb, and request_sock (req). subflow_req is derived from req via mptcp_subflow_rsk(). MP options are extracted via mptcp_get_options(). For MP_CAPABLE, new_msk is cloned from listener->conn using mp_opt data. For MP_JOIN, owner msk comes from subflow_req->msk. The child socket is created by the transport layer's syn_recv_sock(). ctx is derived from child. In MP_JOIN flow, owner reference is transferred to ctx->conn after validation. hmac validation uses keys and nonces from msk and subflow_req.

Verdict: Not Vulnerable

Reviewed region:
[net/mptcp/subflow.c]
```c
static struct sock *subflow_syn_recv_sock(const struct sock *sk,
					  struct sk_buff *skb,
					  struct request_sock *req,
					  struct dst_entry *dst,
					  struct request_sock *req_unhash,
					  bool *own_req)
{
	struct mptcp_subflow_context *listener = mptcp_subflow_ctx(sk);
	struct mptcp_subflow_request_sock *subflow_req;
	struct mptcp_options_received mp_opt;
	bool fallback, fallback_is_fatal;
	struct sock *new_msk = NULL;
	struct sock *child;

	pr_debug("listener=%p, req=%p, conn=%p\n", listener, req, listener->conn);

	/* After child creation we must look for MPC even when options
	 * are not parsed
	 */
	mp_opt.suboptions = 0;

	/* hopefully temporary handling for MP_JOIN+syncookie */
	subflow_req = mptcp_subflow_rsk(req);
	fallback_is_fatal = tcp_rsk(req)->is_mptcp && subflow_req->mp_join;
	fallback = !tcp_rsk(req)->is_mptcp;
	if (fallback)
		goto create_child;

	/* if the sk is MP_CAPABLE, we try to fetch the client key */
	if (subflow_req->mp_capable) {
		/* we can receive and accept an in-window, out-of-order pkt,
		 * which may not carry the MP_CAPABLE opt even on mptcp enabled
		 * paths: always try to extract the peer key, and fallback
		 * for packets missing it.
		 * Even OoO DSS packets coming legitly after dropped or
		 * reordered MPC will cause fallback, but we don't have other
		 * options.
		 */
		mptcp_get_options(skb, &mp_opt);
		if (!(mp_opt.suboptions & OPTIONS_MPTCP_MPC)) {
			fallback = true;
			goto create_child;
		}

		new_msk = mptcp_sk_clone(listener->conn, &mp_opt, req);
		if (!new_msk)
			fallback = true;
	} else if (subflow_req->mp_join) {
		mptcp_get_options(skb, &mp_opt);
		if (!(mp_opt.suboptions & OPTION_MPTCP_MPJ_ACK))
			fallback = true;
	}

create_child:
	child = listener->icsk_af_ops->syn_recv_sock(sk, skb, req, dst,
						     req_unhash, own_req);

	if (child && *own_req) {
		struct mptcp_subflow_context *ctx = mptcp_subflow_ctx(child);

		tcp_rsk(req)->drop_req = false;

		/* we need to fallback on ctx allocation failure and on pre-reqs
		 * checking above. In the latter scenario we additionally need
		 * to reset the context to non MPTCP status.
		 */
		if (!ctx || fallback) {
			if (fallback_is_fatal) {
				subflow_add_reset_reason(skb, MPTCP_RST_EMPTCP);
				goto dispose_child;
			}

			if (fallback)
				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MPCAPABLEPASSIVEFALLBACK);

			subflow_drop_ctx(child);
			goto out;
		}

		/* ssk inherits options of listener sk */
		ctx->setsockopt_seq = listener->setsockopt_seq;

		if (ctx->mp_capable) {
			/* this can't race with mptcp_close(), as the msk is
			 * not yet exposted to user-space
			 */
			inet_sk_state_store((void *)new_msk, TCP_ESTABLISHED);

			/* record the newly created socket as the first msk
			 * subflow, but don't link it yet into conn_list
			 */
			WRITE_ONCE(mptcp_sk(new_msk)->first, child);

			/* new mpc subflow takes ownership of the newly
			 * created mptcp socket
			 */
			new_msk->sk_destruct = mptcp_sock_destruct;
			mptcp_sk(new_msk)->setsockopt_seq = ctx->setsockopt_seq;
			mptcp_pm_new_connection(mptcp_sk(new_msk), child, 1);
			mptcp_token_accept(subflow_req, mptcp_sk(new_msk));
			ctx->conn = new_msk;
			new_msk = NULL;

			/* with OoO packets we can reach here without ingress
			 * mpc option
			 */
			if (mp_opt.suboptions & OPTIONS_MPTCP_MPC)
				mptcp_subflow_fully_established(ctx, &mp_opt);
		} else if (ctx->mp_join) {
			struct mptcp_sock *owner;

			owner = subflow_req->msk;
			if (!owner) {
				subflow_add_reset_reason(skb, MPTCP_RST_EPROHIBIT);
				goto dispose_child;
			}

			if (!subflow_hmac_valid(req, &mp_opt) ||
			    !mptcp_can_accept_new_subflow(subflow_req->msk)) {
				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINACKMAC);
				subflow_add_reset_reason(skb, MPTCP_RST_EPROHIBIT);
				goto dispose_child;
			}

			/* move the msk reference ownership to the subflow */
			subflow_req->msk = NULL;
			ctx->conn = (struct sock *)owner;

			if (subflow_use_different_sport(owner, sk)) {
				pr_debug("ack inet_sport=%d %d\n",
					 ntohs(inet_sk(sk)->inet_sport),
					 ntohs(inet_sk((struct sock *)owner)->inet_sport));
				if (!mptcp_pm_sport_in_anno_list(owner, sk)) {
					SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MISMATCHPORTACKRX);
					goto dispose_child;
				}
				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINPORTACKRX);
			}

			if (!mptcp_finish_join(child))
				goto dispose_child;

			SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_JOINACKRX);
			tcp_rsk(req)->drop_req = true;
		}
	}

out:
	/* dispose of the left over mptcp master, if any */
	if (unlikely(new_msk))
		mptcp_force_close(new_msk);

	/* check for expected invariant - should never trigger, just help
	 * catching eariler subtle bugs
	 */
	if (ctx && ctx->mp_join && ctx->conn)
		 WARN_ON_ONCE(ctx->conn != (struct sock *)subflow_req->msk);

	return child;

dispose_child:
	tcp_rsk(req)->drop_req = true;
	if (child)
		tcp_close(child, 0);
	return NULL;
}
```

Why it is not vulnerable: Dynamically allocated or returned pointers are explicitly checked before dereference: new_msk is checked with 'if (!new_msk) fallback = true' at line 50; ctx is checked with 'if (!ctx || fallback)' at line 66; owner (subflow_req->msk) is checked with 'if (!owner)' at line 94; child is checked with 'if (child && *own_req)' at line 61 and 'if (child)' at the dispose_child label. The subflow_hmac_valid() and mptcp_can_accept_new_subflow() callees receive their msk argument only after the caller verifies 'if (!owner)' at line 94, ensuring the callee's dereferences of msk->remote_key, msk->local_key, and msk->pm.accept_subflow operate on valid pointers. Protocol-stack-derived pointers (listener, subflow_req, tcp_rsk(req)) are assumed valid by the call context (tcp_check_req), and the function relies on this stack-level invariant rather than adding redundant defensive checks.

Security invariants:
- new_msk must be non-NULL before use in MP_CAPABLE branch: enforced by 'if (!new_msk) fallback = true' at line 50, which diverts control to the fallback path where new_msk is never dereferenced.
- ctx must be non-NULL before accessing ctx->setsockopt_seq, ctx->mp_capable, ctx->mp_join: enforced by 'if (!ctx || fallback)' at line 66, which either jumps to 'dispose_child' or 'out' if ctx is NULL.
- owner (subflow_req->msk) must be non-NULL before HMAC validation and mptcp_can_accept_new_subflow(): enforced by 'owner = subflow_req->msk; if (!owner) { ... goto dispose_child; }' at lines 94-97.
- child must be non-NULL before closing in dispose_child: enforced by 'if (child) tcp_close(child, 0)' at line 121.
- subflow_req must be non-NULL before accessing subflow_req->mp_join and subflow_req->mp_capable: enforced implicitly by the call path (tcp_check_req) which only invokes this function for properly initialized MPTCP request sockets.
- msk pointer passed to subflow_hmac_valid() and mptcp_can_accept_new_subflow() must be non-NULL: enforced by the caller's 'if (!owner)' check at line 94, where owner is assigned from subflow_req->msk before the calls at lines 100-101.

Invariant verification:
- NULL check on dynamically cloned msk before use: holds=true. Evidence: Line 50: 'if (!new_msk) fallback = true;' ensures new_msk is either valid or fallback path is taken where new_msk is not dereferenced.
- NULL check on child socket's MPTCP context before field access: holds=true. Evidence: Line 66: 'if (!ctx || fallback)' guards all subsequent accesses to ctx->setsockopt_seq, ctx->mp_capable, and ctx->mp_join.
- NULL check on MP_JOIN owner msk before HMAC validation and subflow acceptance check: holds=true. Evidence: Lines 94-97: 'owner = subflow_req->msk; if (!owner) { ... goto dispose_child; }' ensures owner is non-NULL before the calls to subflow_hmac_valid() and mptcp_can_accept_new_subflow() at lines 100-101.
- Caller-guaranteed safety for callee pointer dereferences in subflow_hmac_valid and mptcp_can_accept_new_subflow: holds=true. Evidence: Both callees dereference their msk parameter (msk->remote_key, msk->local_key, msk->pm.accept_subflow). The caller at line 94 checks 'if (!owner)' where owner equals subflow_req->msk, and passes the same subflow_req->msk value to both callees. This ensures the msk argument is non-NULL.
- Safe disposal of child socket on error path: holds=true. Evidence: Line 121: 'if (child) tcp_close(child, 0)' ensures child is checked before close, and line 119 'tcp_rsk(req)->drop_req = true;' is reached only after child validity is confirmed.
- Cleanup of leftover new_msk at function exit: holds=true. Evidence: Lines 113-114: 'if (unlikely(new_msk)) mptcp_force_close(new_msk);' disposes any orphaned msk before returning.

Residual risk notes: The function does not perform explicit NULL checks on listener (mptcp_subflow_ctx(sk)) or subflow_req (mptcp_subflow_rsk(req)), relying instead on the protocol stack invariant that tcp_check_req only invokes this function for properly initialized MPTCP sockets. This is consistent with kernel network stack design where upper-layer handlers assume lower-layer validation. Additionally, subflow_hmac_valid() and mptcp_can_accept_new_subflow() do not defensively check their msk parameter internally, relying on caller-side validation. If an unrelated code path were to call these functions with a NULL argument, a dereference would occur, but no such call path exists in the supplied context.

An analysis of the control and data flow reveals a Use-After-Free (UAF) vulnerability during the fallback path of an MPTCP subflow connection.

### Vulnerability Analysis
In `subflow_syn_recv_sock()`, when processing a new child socket, the local pointer `ctx` is assigned the MPTCP context of the socket:
```c
struct mptcp_subflow_context *ctx = mptcp_subflow_ctx(child);
```
If a fallback condition triggers and is not considered fatal (`!ctx || fallback` and `!fallback_is_fatal`), the code appropriately drops the MPTCP context via `subflow_drop_ctx(child)`:
```c
		if (!ctx || fallback) {
			if (fallback_is_fatal) {
				subflow_add_reset_reason(skb, MPTCP_RST_EMPTCP);
				goto dispose_child;
			}

			if (fallback)
				SUBFLOW_REQ_INC_STATS(req, MPTCP_MIB_MPCAPABLEPASSIVEFALLBACK);

			subflow_drop_ctx(child);
			goto out;
		}
```
The function `subflow_drop_ctx()` frees the memory associated with this context and nullifies the pointer inside the socket structure. However, the local variable `ctx` still retains the stale, now-freed pointer value.

The code then branches to the `out` label, where it performs an invariant check for debugging purposes:
```c
out:
	/* dispose of the left over mptcp master, if any */
	if (unlikely(new_msk))
		mptcp_force_close(new_msk);

	/* check for expected invariant - should never trigger, just help
	 * catching eariler subtle bugs
	 */
	if (ctx && ctx->mp_join && ctx->conn)
		 WARN_ON_ONCE(ctx->conn != (struct sock *)subflow_req->msk);
```
Because `ctx` is non-NULL (it simply hasn't been cleared locally), the condition evaluates `ctx->mp_join` and potentially `ctx->conn`. This constitutes a read from freed memory (Use-After-Free).

### Exploitability and Impact
While typically isolated to a memory read in the kernel (leading to potential kernel panics/denial-of-service if the unmapped memory is accessed or a poisoned slab is tripped), an attacker who controls the timing of a reallocation over the freed subflow context could potentially influence execution flow. The preconditions merely require establishing an MPTCP connection that naturally triggers a non-fatal fallback (such as a missing MP_CAPABLE option during certain handshake sequences), which an unauthenticated remote attacker can easily induce.

### Verdict
The code is vulnerable to a Use-After-Free (CWE-416) resulting from a dangling local pointer being accessed after the underlying context memory has been legitimately destroyed.

```json
{
  "vulnerable": true,
  "cwe": "CWE-416",
  "severity": "High",
  "reviewed_region": "net/mptcp/subflow.c: subflow_syn_recv_sock",
  "vulnerable_region": "net/mptcp/subflow.c:160-165",
  "root_cause": "The pointer `ctx` points to the MPTCP context which is explicitly freed by `subflow_drop_ctx(child)` on the fallback path. When control jumps to the `out` label, the code checks `if (ctx && ctx->mp_join && ctx->conn)`, which dereferences the now-freed `ctx` pointer.",
  "exploitability": "Exploitable if compiled, though it appears `ctx` is scoped to the `if` block, which would typically cause a compiler error for being out of scope at the `out` label. Assuming compilation succeeds (e.g. via scoping differences or function-level declaration in the actual build), an attacker could trigger a non-fatal fallback (such as omitting MP_CAPABLE in an out-of-order packet), forcing the context to be dropped. The subsequent read from the freed chunk at the `out` label causes a Use-After-Free.",
  "attack_preconditions": "The attacker must initiate an MPTCP connection that causes `fallback` to be true but `fallback_is_fatal` to be false (e.g., via MP_CAPABLE mismatch or missing options), forcing the execution path through `subflow_drop_ctx()` and `goto out;`.",
  "impact": "If compiled and executed, this memory corruption (read) can result in a kernel panic (Denial of Service) or potentially be leveraged to leak information or influence control flow depending on how the freed slab is reallocated between the free and the check.",
  "non_vulnerable_reason": "",
  "security_invariants": "",
  "invariant_verification": "",
  "residual_risk_notes": "The code snippet as provided declares `ctx` inside an `if` block but uses it at the `out` label outside that block, which would result in a compiler error. This typically prevents the vulnerable code from being deployed.",
  "call_path": "tcp_v4_rcv -> tcp_check_req -> subflow_syn_recv_sock -> mptcp_can_accept_new_subflow"
}
```


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/pxlrbt/filament-excel
Language: PHP
File: routes/web.php
Function: filament-excel-download

Call path: Route::get (routes/web.php) → Route closure (routes/web.php) → Storage::disk('filament-excel')->path (routes/web.php) → response()->download (routes/web.php)

### Primary Function

```php
function (string $path) {
    return
        response()
            ->download(Storage::disk('filament-excel')->path($path), substr($path, 37))
            ->deleteFileAfterSend();
}
```

### Cross-File Context

[Illuminate\Support\Facades\Storage — import — routes/web.php:4]
use Illuminate\Support\Facades\Storage;

[Route::get — entry — routes/web.php:3-10]
function (string $path) { return response() ->download(Storage::disk('filament-excel')->path($path), substr($path, 37)) ->deleteFileAfterSend(); }

Control flow: HTTP GET request enters via Route::get, path parameter is passed to closure which calls Storage::disk()->path() and passes result to response()->download() which serves file content.

Data flow: User-controlled $path parameter flows directly from route parameter through closure to Storage::disk()->path() to response()->download(). No validation or sanitization in pre-fix version.

Verdict: Vulnerable
Vulnerable region:
[routes/web.php]
```php
<?php

Route::get('filament-excel/{path}', function (string $path) {
    return
        response()
            ->download(Storage::disk('filament-excel')->path($path), substr($path, 37))
            ->deleteFileAfterSend();
})
    ->where('path', '.*')
    ->name('filament-excel-download');
```
CWE: CWE-22
Severity: MEDIUM

Root cause: Missing authorization check on file download route. The /filament-excel/{path} endpoint allowed unauthenticated access to arbitrary files through the path parameter. Without URL signature validation (signed middleware), attackers could access files by constructing URLs with path traversal payloads or simply knowing valid file paths.

Exploitability: Attacker sends GET request to /filament-excel/{path} with path traversal payload or known file path. No authentication or valid signature required in pre-fix version.

Attack preconditions:
- Attacker must be able to send HTTP requests to the application
- Attacker must know or guess valid file paths on the 'filament-excel' disk
- No authentication needed for pre-fix version

Likely impact: Attacker sends GET request to /filament-excel/{path} with path traversal payload or known file path. No authentication or valid signature required in pre-fix version.

Route::get
Route closure
Storage::disk('filament-excel')->path
response()->download

Based on the analysis of the provided code and context, there is a severe **Path Traversal (CWE-22)** vulnerability that leads to **Arbitrary File Read** and **Arbitrary File Deletion**.

### Vulnerability Explanation
The route defines a closure that takes a user-controlled `$path` variable directly from the URL. This variable is passed to `Storage::disk('filament-excel')->path($path)`.

In Laravel, calling the `path()` method on a local storage disk merely concatenates the disk's root path with the provided `$path` string without performing any path normalization or validation. Flysystem's internal traversal protections (which usually apply to methods like `get()` or `put()`) are bypassed because `path()` simply returns the raw, concatenated string path.

This string is then passed to `response()->download()`, which reads and serves the file using Symfony's underlying `BinaryFileResponse`. By supplying a payload with directory traversal sequences (e.g., `..%2f..%2f..%2f.env`), an attacker can break out of the `filament-excel` storage directory and target arbitrary files on the server's filesystem.

To make matters worse, the chained `->deleteFileAfterSend()` method instructs the framework to delete the file once the download is complete. This means an attacker can not only read sensitive files (like the Laravel `.env` file, configuration files, or source code) but also permanently delete them, potentially causing catastrophic data loss and denial of service.

### Attack Preconditions
- The web server and Laravel routing must allow URL-encoded path separators (e.g., `%2F` or `%5C`) or the route must be configured to allow forward slashes in the parameter (e.g., using `->where('path', '.*')`).
- The application process must have sufficient filesystem permissions to read and delete the targeted files.

### Impact
- **Arbitrary File Read:** An attacker can download sensitive files, resulting in a total compromise of application secrets, database credentials, and source code.
- **Arbitrary File Deletion:** An attacker can delete critical application files or system files, causing a complete denial of service (DoS) and data destruction.

### Verdict
The code is strictly **vulnerable** to Path Traversal (CWE-22), leading to arbitrary file read and deletion. The root cause is the direct use of unvalidated and unsanitized user input in a file path resolution and deletion mechanism.

```json
{
  "vulnerable": true,
  "cwe": "CWE-22",
  "severity": "CRITICAL",
  "reviewed_region": "function (string $path) {\n    return\n        response()\n            ->download(Storage::disk('filament-excel')->path($path), substr($path, 37))\n            ->deleteFileAfterSend();\n}",
  "vulnerable_region": "response()\n            ->download(Storage::disk('filament-excel')->path($path), substr($path, 37))\n            ->deleteFileAfterSend();",
  "root_cause": "The route handler takes user-provided `$path` directly from the request and uses it to construct a file path via `Storage::disk()->path($path)` without sanitizing directory traversal characters. It then downloads and subsequently deletes the resolved file.",
  "exploitability": "Highly exploitable. An attacker can craft a URL containing directory traversal sequences (like `..%2f` or `..\\`) in the `path` parameter. The server will resolve this to arbitrary files outside the intended storage directory.",
  "attack_preconditions": "The server must allow URL-encoded slashes or backslashes in the request URL, or the Laravel route must have been defined to allow slashes in the parameter constraint. The application must have read and write/delete permissions for the targeted files.",
  "impact": "Arbitrary File Read and Arbitrary File Deletion. An attacker can read sensitive files (e.g., `.env`, configuration, source code) and delete them, leading to total compromise of secrets and catastrophic Denial of Service.",
  "non_vulnerable_reason": null,
  "security_invariants": null,
  "invariant_verification": null,
  "residual_risk_notes": null,
  "call_path": [
    "Route::get (routes/web.php)",
    "Route closure (routes/web.php)",
    "Storage::disk('filament-excel')->path (routes/web.php)",
    "response()->download (routes/web.php)"
  ]
}
```

Highly exploitable. An attacker can craft a URL containing directory traversal sequences (like `..%2f` or `..\`) in the `path` parameter. The server will resolve this to arbitrary files outside the intended storage directory.