Skip to content
Business logic Audit finding Advanced

Permissionless retry chained with attempt termination denies the owner of a latched position protection its only amend window and locks the protected position for as long as a third party pays gas

A latched position protection whose trader-set close ceilings cannot be met by the market fails every close attempt and returns to Latched, where the owner's only remedy is to amend the ceilings. Because terminalising a failed attempt and retrying are both permissionless and can be chained in one transaction, a third party can keep the protection permanently in Triggered state, denying the owner the amend window and locking the position open indefinitely.

abarbatei Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#98038 [SC-High] Permissionless retry chained with attempt termination denies the owner of a latched position protection its only amend window and locks the protected position for as long as a third party pays gas

Submitted on Nov 4th 2026 at 15:03:38 UTC by @abarbatei for Audit Competition | Plether

Description

Brief/Intro

A take-profit or stop-loss protection whose trader-chosen close ceilings cannot be satisfied by the market close fails every attempt and returns to Latched. The protocol's only owner remedy in that state is PositionProtectionBook::amendLatchedPositionProtectionCloseLimits, which requires status Latched and an empty account order queue. Both facts are controlled by anyone: terminal failure of the live attempt (expiry, or a deterministic ceiling violation at the queue head) and the retry that re-queues a fresh attempt are permissionless, carry no owner priority and no cooldown, and compose in one transaction. A third party that terminalizes the live attempt and immediately retries in the same transaction makes sure no block ever ends in the amendable state. Because every ordinary order commit is rejected while a protection is active and a Triggered or Latched protection can be neither cancelled nor replaced, the owner cannot amend, close, reduce, cancel or replace the protected position for as long as the attacker pays about 0.9 million gas per minute. The proof sustains the lock through 64 consecutive cycles (more than one hour of chain time), with 129 owner amend transactions reverting at every point they could be sent, and shows the position closing in the first block after the attacker stops.

Vulnerability Details

Intended behaviour

A protection stores four financial ceilings chosen by the trader (execution notional, gross account debit, action charge, explicit fees). When a trigger fires, the Router queues a full-position market close that copies those ceilings; if the close fails for a non-liquidation reason while the exact position remains, the protection returns to Latched and anyone may queue a fresh attempt with PositionProtectionBook::retryPositionProtectionClose. The ceilings are a security property (the protocol added them so keepers cannot close a trader under worse economics than the trader authorized), and the owner is expected to relax them when they bind. The canonical entrypoint list states it in CANONICAL_ENTRYPOINTS.md#L145-L148: "The owner may amend the close ceilings of a Latched protection ... when the account has no pending Router order", and the retry is described in CANONICAL_ENTRYPOINTS.md#L257-L259 as "permissionless, nonpayable, and valid only when the protection has no live attempt". The deployment guide tells honest keepers to "investigate planner, constraint, or other persistent failures before retrying; do not continuously queue the same failing attempt" (DEPLOYMENT.md#L416-L421). The program rules state that keepers are not trusted and that harm caused by any caller acting as a keeper is in scope.

Root cause

The owner's amend requires two facts at once, in the PositionProtectionBook::amendLatchedPositionProtectionCloseLimits function:

Solidity
    function amendLatchedPositionProtectionCloseLimits(
        uint64 protectionId,
        PositionProtectionTypes.CloseFinancialLimits calldata limits
    ) external nonReentrant {
        StoredProtection storage protection = _ownedActiveProtection(protectionId, msg.sender);
        if (protection.status != PositionProtectionTypes.PositionProtectionStatus.Latched) {
            revert OrderRouter__ProtectionNotLatched();
        }
        if (IPositionProtectionRouterHost(ROUTER).pendingOrderCounts(msg.sender) != 0) {
            revert OrderRouter__PendingOrdersExist();
        }
        _setCloseLimits(protection, limits);
        _emitCloseLimitsUpdated(protection);
    }

The retry has no owner check (_activeProtection instead of _ownedActiveProtection), no block or time gate, and consumes exactly the state the amend needs, in the PositionProtectionBook::retryPositionProtectionClose function:

Solidity
    function retryPositionProtectionClose(
        uint64 protectionId
    ) external nonReentrant returns (uint64 linkedOrderId) {
        StoredProtection storage protection = _activeProtection(protectionId);
        if (protection.status != PositionProtectionTypes.PositionProtectionStatus.Latched) {
            revert OrderRouter__ProtectionNotLatched();
        }
        _requireMatchingPosition(protection);

        IPositionProtectionRouterHost router = IPositionProtectionRouterHost(ROUTER);
        if (router.pendingOrderCounts(protection.account) != 0) {
            revert OrderRouter__PendingOrdersExist();
        }

        if (protection.linkedOrderId == 0 || _attemptProtectionIds[protection.linkedOrderId] != 0) {
            revert PositionProtectionBook__InvalidLinkedOrder();
        }
        uint64 expectedOrderId = router.nextCommitId();
        linkedOrderId = IPositionProtectionCloseAttemptHost(ROUTER)
            .commitProtectionCloseAttempt(protectionId, protection.account, protection.side, protection.size);
        if (linkedOrderId != expectedOrderId) {
            revert PositionProtectionBook__InvalidHostResponse();
        }
        _recordCloseAttempt(protection, linkedOrderId);
    }

The retried close reuses the stored ceilings unchanged, in the OrderLiquidationBatchLogic::_protectionCloseRequest lines 666-677 function:

Solidity
        request.sizeDelta = size;
        request.targetPrice = side == CfdTypes.Side.LONG ? host.engine().CAP_PRICE() : 1;
        request.isClose = true;
        request.bounds.submitBy = uint64(block.timestamp);
        request.bounds.executionWindowSeconds = uint32(host.maxExecutionWindowSeconds());
        request.bounds.allowedExecutionModes = ALL_V3_EXECUTION_MODES;
        request.bounds.expectedConfigHash = bytes32(0);
        request.bounds.maxExecutionBountyAssets = 0;
        request.bounds.maxExecutionNotionalAssets = limits.maxExecutionNotionalAssets;
        request.bounds.maxGrossAccountDebitAssets = limits.maxGrossAccountDebitAssets;
        request.bounds.maxActionChargeAssets = limits.maxActionChargeAssets;
        request.bounds.maxExplicitFeesAssets = limits.maxExplicitFeesAssets;

Terminalization of the live attempt is also permissionless, by two routes. After the 60-second execution window, an expired attempt can be cleared by id even behind a live FIFO head, in the OrderRecoverySidecar::clearInvalidOrders lines 84-91 function (the public entrypoint is OrderRouter::clearInvalidOrders):

Solidity
            uint64 orderId = orderIds[nextIndex];
            OrderV3Types.PendingIntent memory pending = book.pendingIntent(orderId);
            if (pending.account == address(0)) {
                continue;
            }

            bytes32 observedConfigHash = book.currentExecutionConfigHash();
            bool expired = block.timestamp > pending.timing.executionDeadline;

Inside the window, executing the attempt at the queue head with any qualifying tick makes the policy evaluator raise a typed ConstraintViolation when the trader's ceiling binds, which the Router classifies as terminal. For the gross-debit ceiling the assessed quantity is the realized loss plus carry and charges, in the CfdOrderPolicyEvaluatorBase::_assessClose lines 409-411 function:

Solidity
        assessment.executionNotionalAssets = CfdMath.sizeToLots(delta.sizeDelta) * delta.price;
        assessment.grossAccountDebitAssets = delta.pricePnlClaimConsumedAssets + delta.pricePnlPledgeConsumedAssets
            + delta.realizedCarryAssets + delta.actionChargeCollectedAssets + executionBountyAssets;

and the bound is enforced in the CfdOrderPolicyEvaluatorBase::_enforceBounds lines 504-507 function:

Solidity
        _requireMaximum(
            OrderV3Types.ConstraintKind.GrossAccountDebit,
            assessment.grossAccountDebitAssets,
            bounds.maxGrossAccountDebitAssets

Either route settles the attempt as failed and the Router hands it back to the Book, in the OrderRouter::_settleTerminalBounty lines 324-329 function:

Solidity
        if (!success && lifecycleBook.isProtectionAttempt(order.orderId)) {
            if (bountyAssets != 0) {
                revert OrderRouter__ProtectedCloseBountyNonzero(bountyAssets);
            }
            positionProtectionBook.handleFailedProtectionAttempt(order.orderId, order.account, reason);
        }

which relatches because the exact position still exists, in the PositionProtectionBook::handleFailedProtectionAttempt lines 662-667 function:

Solidity
        delete _attemptProtectionIds[orderId];
        retained = _positionMatches(protection);
        emit PositionProtectionCloseAttemptFailed(protectionId, account, orderId, reason, retained);
        if (retained) {
            protection.status = PositionProtectionTypes.PositionProtectionStatus.Latched;
            return true;

The Router record is deleted in the same frame, so the account queue is empty for the rest of that transaction. An attacker contract that calls the terminalization and then retryPositionProtectionClose in one transaction therefore leaves every block in the state Triggered with one live child. Meanwhile the owner's other exits are closed by design. Cancellation accepts only PendingOpen or Armed, in the PositionProtectionBook::_cancel lines 413-418 function (the same status rule gates PositionProtectionBook::replacePositionProtection through its internal status rule, and PositionProtectionBook::cancelPositionProtectionAndCommitClose requires Armed):

Solidity
        PositionProtectionTypes.PositionProtectionStatus status = protection.status;
        if (
            status != PositionProtectionTypes.PositionProtectionStatus.PendingOpen
                && status != PositionProtectionTypes.PositionProtectionStatus.Armed
        ) {
            revert OrderRouter__ProtectionNotArmed();

and every public order commit is refused while any protection is active, in the OrderLiquidationBatchLogic::_validateFreshRequest lines 313-315 function:

Solidity
        if (enforceProtectionLock && host.positionProtectionBook().activePositionProtectionId(account) != 0) {
            revert OrderRouter__ProtectionActive();
        }

So the amend is the owner's only remedy, and its precondition is a state that any third party can make unobservable.

Attack sequence

  1. A trader holds a 300,000 USDG notional LONG position and arms a stop loss at 1.02 with maxGrossAccountDebitAssets set to the loss it expects at the stop plus the execution fee, with a 10% buffer (6,734.64 USDG). All other ceilings are unlimited.
  2. The market moves through the stop to 1.03. Any keeper triggers the protection (the attacker does, and collects the trigger bounty). The queued close now carries a gross debit of 9,123.6 USDG, above the ceiling, so every attempt fails with ConstraintViolation(GrossAccountDebit) and relatches.
  3. Route A, inside the attempt window: within seconds of each commit the attacker's contract executes the attempt at the head with a qualifying Pyth tick (terminal failure, relatch) and calls retryPositionProtectionClose in the same transaction. The attempt never reaches its deadline, so the owner's oracle-free expireOrder reverts OrderRouter__OrderNotExpired in every block.
  4. Route B, oracle-free: the attacker lets the 60-second window lapse, then calls clearInvalidOrders([child]) and retryPositionProtectionClose in one transaction.
  5. Every block ends Triggered with one live child. The owner's amendLatchedPositionProtectionCloseLimits reverts OrderRouter__ProtectionNotLatched whether sent before the attacker's transaction, after it, or after the owner's own expireOrder (the attacker's clear is then a no-op and its retry still succeeds). commitOrder with a close reverts OrderRouter__ProtectionActive; cancelPositionProtection, cancelPositionProtectionAndCommitClose and replacePositionProtection revert OrderRouter__ProtectionNotArmed.
  6. The attacker repeats step 3 or 4 once per attempt for as long as it is willing to pay gas. The position stays open at the trader's full exposure. The trader can still withdraw free settlement and can still be liquidated.

Why the owner cannot counter

The amendable state (Latched, empty queue) exists only between a terminalization and the next retry. Nothing gives the owner priority over a third party in that interval: the retry has no owner check, no cooldown and no block gate, and the Book has no owner-only terminalize-and-amend action. An owner who sends one call per transaction (an externally owned account, or a smart account driven by the protocol's SDK, whose amend action plan is a single call and whose expiry and retry builders are keeper calls) needs its amend sequenced at a point where the state holds. The attacker's cycle transaction is valid at every such point: on an attempt that is still pending it terminalizes and retries, on an attempt the owner has just expired the clear is a no-op and the retry still re-queues. Arbitrum's sequencer orders transactions by arrival; the attacker wins a cycle whenever its transaction is sequenced between the owner's terminalization and the owner's amend. Against a wallet user, whose two confirmations are seconds apart and whose interface never shows the window, one cycle transaction per L2 block suffices; against a scripted owner that submits both calls back to back the attacker must submit at a higher rate than the owner's gap between transactions, which raises its gas cost but not the owner's options. On route A the owner's only oracle-free terminalization never becomes available at all. A wallet user cannot even see the window: no block ever exposes it, so an interface that enables actions from chain state never offers the amend. An owner who writes a custom contract or batch that terminalizes, amends and retries atomically turns each cycle into a first-arrival race at the sequencer; the attacker cannot bound its win streak against such an owner, but that owner must know the race exists, hold a batching account, and on route A hold a signed Pyth payload for the 15-second settlement window of every attempt. The production trading account is a smart account that can batch calls, so the shortfall is in the shipped action plans and interface, not in the account type; a batching owner turns each cycle into a race the attacker cannot bound. This report claims the lock against the single-call owner class, which is every owner using the shipped SDK plans, the web interface, or an externally owned account.

Preconditions and how the failing ceiling arises

The attacker needs no role, no capital in the protocol and no price manipulation; it pays gas. The only precondition is a stored ceiling that the market close cannot meet, and the ceilings exist precisely so that traders set them: the protocol's integration guide tells callers to use the unlimited sentinel "only when your account policy intentionally permits that exposure" and requires four explicit close limits on every protection (packages/perps/WORKING_WITH_AI_AGENTS.md), and the client SDK supplies no default for them. The current web interface exposes only trigger prices and does not offer the amend for a latched protection, so the affected population is SDK and agent users, the class the guide addresses. The proof uses the most ordinary case: a stop loss whose gross-debit bound is the loss the trader expected at the stop, breached by a 1% move beyond the stop. Other sources of the same state, all without any attacker involvement: a maxExplicitFeesAssets sized to the 4 bps execution fee fails every frozen-market close, because the 50 bps frozen-close spread enters explicit fees; a maxExecutionNotionalAssets at creation-time notional fails the stop leg of every LONG, because that leg only triggers at a higher price; an owner fee increase after its timelock pushes charges past any ceiling sized before it. The precondition text of the prior audit's own finding on the ceilings names this drift: "execution happens later under worse carry, fee, or frozen-spread conditions than when the user originally set the protection" (audit finding MED-9). One source does not qualify and is excluded from this report: a ceiling breached only by accrued carry can be defused by the owner with a plain settlement deposit, which realizes carry before the next attempt.

Why this is not an accepted limitation

The permissionless retry was introduced with the statement that "poorly timed retries can add FIFO and gas pressure through repeated expiry cycles" and that it "allows third parties to enqueue attempts at suboptimal times" (plether-core pull request 78). That acceptance contemplates queue and gas pressure, and it predates the owner amend path, which was added by pull request 124 with the assumption that "the owner may amend limits after relatch". The audit acceptance of the ceilings (MED-9) relies on the same assumption: "Tight limits may prevent execution until conditions improve or the owner amends them." The repository's keeper limitations (SECURITY.md#L1356-L1359) accept the opposite regime: "Liveness depends on keepers processing the terminal attempt and separately appending a retry, and operators must alert on prolonged Latched state without a live child", that is, keeper inactivity, which an alert can detect. None of these texts describes a third party keeping the queue permanently non-empty so that the owner-only amend, the remedy those acceptances rely on, is unreachable; an alert on prolonged Latched never fires here because the protection is Triggered at every block boundary. The atomic owner exit added for MED-30 explicitly excludes Triggered and Latched records, which is why no alternative exit exists.

Impact Details

Selected impact: Griefing (no profit motive for an attacker, but damage to the users or the protocol), Medium under the program's custom list.

The attacker earns nothing from the cycle (retries carry no bounty; the trigger bounty is paid once and would have gone to whichever keeper triggered). The victim loses every voluntary control over an open leveraged position: it cannot close at the market, cannot reduce, cannot relax or tighten its stop, cannot cancel the protection, and cannot replace it. Its position margin stays committed and its full market exposure persists. The remaining exits are the market coming back inside the trader's own bound, the attacker stopping, or liquidation, which charges the liquidation fee and pays the liquidator.

Measured in the proof at the release parameters:

Quantity Value
Protected position 300,000 USDG notional LONG, 29,580 USDG margin
Trader's gross-debit ceiling 6,734.64 USDG (expected 6,122.4 USDG at the stop, plus 10%)
Loss plus execution fee of the close at the breach price 1.03 (the assessed gross debit also adds accrued carry) 9,123.6 USDG
Consecutive attacker cycles 64 (3 execute-fail, 61 expiry)
Chain time the owner was locked out 3,724 seconds
Owner amend transactions, all reverted 129
Attacker gas per expiry cycle (measured in-contract) 908,964 average, 684,920 to 937,824
Attacker gas per execute-fail cycle 1,195,188
Gas measurement in-contract; intrinsic and calldata cost excluded
Loss the trader asked to realize when first denied 9,000 USDG
Loss realized once the lock ended (market at 1.05) 15,000 USDG (15,136 USDG debited including fee and carry)

At one expiry cycle per minute the attacker spends about 1.3 billion gas per day. At Arbitrum One's 0.01 gwei base-fee floor that is about 0.013 ETH per day before the small L1 data component, that is, tens of dollars per day per victim, against a victim whose entire position exposure is frozen. A development run of the same loop with a raised test gas limit (not included here) sustained 1,443 cycles, 88,023 seconds, and met no protocol limit, so the duration is bounded only by the attacker's willingness to pay. The proof also satisfies the program's "Temporary freezing of funds for at least 1 hour" wording for the position margin; Griefing is selected because it does not depend on a duration threshold.

Mitigation

Give the owner a path to the amend that no third party can pre-empt. The smallest change that addresses the root cause: drop the empty-queue requirement from amendLatchedPositionProtectionCloseLimits and accept both Triggered and Latched. The amended ceilings are stored on the protection and are read only when the next attempt is built by _protectionCloseRequest, so a live child keeps the bounds it already copied and the next retry picks up the new ones; no queue invariant is touched. With that change the attacker's cycle no longer denies anything, because the owner amends at any time and the attacker's own next retry executes with the amended limits.

Solidity
    function amendLatchedPositionProtectionCloseLimits(
        uint64 protectionId,
        PositionProtectionTypes.CloseFinancialLimits calldata limits
    ) external nonReentrant {
        StoredProtection storage protection = _ownedActiveProtection(protectionId, msg.sender);
        PositionProtectionTypes.PositionProtectionStatus status = protection.status;
        if (
            status != PositionProtectionTypes.PositionProtectionStatus.Latched
                && status != PositionProtectionTypes.PositionProtectionStatus.Triggered
        ) {
            revert OrderRouter__ProtectionNotLatched();
        }
        _setCloseLimits(protection, limits);
        _emitCloseLimitsUpdated(protection);
    }

If the design wants the live child to use the new limits at once, add an owner-only amendAndRetryPositionProtectionClose that expires or cancels the live child, stores the limits and queues the retry in one call. Independently, a short owner-priority window after each terminal attempt (a permissionless retry admitted only once a few blocks have passed since the previous attempt's terminal block, while the owner may retry immediately) removes the atomic composition that this report relies on.

References

Proof of Concept

Proof of Concept

Setup. The proof is a Foundry test in the repository's own perps test suite at the pinned commit a82d4fefb02768e5b3bddcc97dee371eee24fea8. It extends the existing fixture packages/perps/test/perps/BasePerpTest.sol (release carry rate, mock USDG, mock Pyth) and modifies no contract in scope. Place the file at `packages/perps/test/poc/latched-amend-denial/ProofPermissionlessRetryDeniesLatchedAmend.t

The original report as published on Immunefi, by abarbatei. Images and videos are our own copies; raw HTML is shown as text. View it on Immunefi.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

The owner-only amend requires the protection to be Latched with an empty order queue, but both terminalising the live attempt and re-queuing a retry are permissionless and composable in one transaction, so a third party can make that state unobservable.

Impact

The victim loses every voluntary control over an open leveraged position and its margin stays committed, though the text notes a batching owner can turn each cycle into a race the attacker cannot bound, and the lock is claimed only against single-call owners.

What the attacker needed

A stored close ceiling the market cannot meet; attacker pays gas each cycle; no role or capital needed

The fix

The owner should be given a path to the amend that no third party can pre-empt, for example by dropping the empty-queue requirement from the amend function.

How it was found

  1. A trader arms a stop loss whose gross-debit ceiling is the expected loss at the stop plus a buffer.
  2. The market moves past the stop so the queued close exceeds the ceiling and every attempt fails with a constraint violation and relatches.
  3. The attacker executes the attempt at the queue head with a qualifying price tick, causing terminal failure and relatch, then calls the retry in the same transaction.
  4. Alternatively the attacker lets the execution window lapse, then clears the expired order and retries in one transaction.
  5. Every block ends with the protection Triggered and one live child, so the owner's amend reverts and all other exits are refused.
  6. The attacker repeats the cycle for as long as it pays gas, keeping the position open.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

A trader can attach a safety order to their leveraged position that closes it automatically, but only within price limits the trader chose. If the market moves past those limits the automatic close keeps failing, and the trader is supposed to be able to loosen the limits. The report shows that anyone can repeatedly fail and re-queue that close in a single transaction, so the brief moment when loosening is allowed never appears on chain, and the trader cannot close, reduce or cancel the position.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by abarbatei

View all

15 more disclosed reports, best first.

More from Plether

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.