Skip to content
DoS Audit finding Advanced

Guardian share replay overwrite causes persistent recovery DoS (missing session binding)

Guardian shares uploaded for social recovery were stored without binding them to the recovery session, so an attacker could replay old shares to overwrite fresh ones. This made the shares undecryptable in the current session and could persistently block recovery.

czarcas7ic Follow with 0xsolisec, Ahmerdrarerh and 29 others

Originally disclosed on Code4rena

Submitted by czarcas7ic, also found by 0xsolisec, Ahmerdrarerh, ameng, Bala1796, bunnyhunter, codertjay, Dest1ny_rs, eloujoe, Evo, felconsec, Guilherme, HalfBloodPrince, happykilling, hecker_trieu_tien, hodlturk, IndominusFortune, JuggerNaut63, Khan2018, kmkm, MakeIChop, niffylord, nstatoshi, odeili, pashap9990, psyone, Rhaydden, richa, ScientificKatie420, swordfish, Vivekz, and Yifan

  • contracts/src/http/endpoints/reconstruction/upload_share.rs #L52-L67
  • lib/src/backup/v0.rs #L342-L354

This finding concerns the guardian share upload endpoint used during social recovery, implemented in contracts/src/http/endpoints/reconstruction/upload_share.rs.

The handler currently accepts any valid GuardianShare for a given (account_id, backup_id) and blindly overwrites any existing share for that guardian index:

pub fn handler(
    mut ctx: OffChainContext,
    state: ContractState,
    request: HttpRequestData,
    _params: Params,
) -> Result<HttpResponseData, ContractError> {
    let request: Request = deserialize_request_body(&request)?;
    // ...
    // The share id will be in the range [0, |shares|)
    let share_id = backup
        .verify(&request.share.0)
        .map_err(|_| ServerError::InvalidParameter("Invalid guardian share".to_string()))?;

    // Update the share mapping for this backup
    // usually, the share will not already exist in this map:
    // we allow overwriting in case of a buggy client library and to
    // simplify a client which fails during the upload process: it can simply retry all uploads.
    //
    // Potentially different multiple versions of the same share are all equivalent.
    // Hence no replay protection is required here.
    let storage_key = (account_id, backup_id);
    let mut shares = GuardianShareCollection::load(&mut ctx, storage_key).unwrap_or_default();
    shares.insert(share_id, request.share.0);  // overwrites existing share
    GuardianShareCollection::store(&mut ctx, storage_key, shares);
    …
}

GitHub permalink: contracts/src/http/endpoints/reconstruction/upload_share.rs#L33-L74

The in-code comment that “potentially different multiple versions of the same share are all equivalent” is correct at the level of the underlying Shamir share, but it no longer holds for recovery sessions once shares are encrypted to per-session recovery_pke keys—ciphertexts from different sessions are not interchangeable for the current recovery.

Root cause

At a cryptographic level, a GuardianShare is:

  • A Shamir share for the backup, plus
  • A signature and ciphertext that bind the share to a specific recovery public key (recovery_pke):
// GuardianShare construction for recovery
impl DecryptedShareV0 {
    pub fn send_for_recovery<R: Rng + CryptoRng>(
        &self,
        rng: &mut R,
        owner: &AccountState,
    ) -> Result<GuardianShare, SwafeError> {
        let recovery_pke =
            match owner {
                AccountState::V0(state) => state.rec.pke.as_ref().ok_or_else(|| {
                    SwafeError::InvalidOperation("Recovery not started".to_string())
                })?,
            };
        let ct = recovery_pke.encrypt(rng, &self.share.share, &EmptyInfo);
        let sig = self.share.sk.sign(
            rng,
            &SignedEncryptedShare {
                ct: &ct,
                idx: self.idx,
            },
        );
        Ok(GuardianShare::V0(GuardianShareV0 {
            ct,
            idx: self.idx,
            sig,
        }))
    }
}

GitHub permalink: lib/src/backup/v0.rs#L154-L179 – send_for_recovery

Recovery is session-bound:

  • Each recovery initiation generates a fresh asymmetric keypair used only for that recovery attempt:
impl AccountStateV0 {
    /// Initiate recovery using the RIK from offchain nodes
    pub fn initiate_recovery<R: Rng + CryptoRng>(
        &self,
        rng: &mut R,
        acc: AccountId,
        rik: &RecoveryInitiationKey,
    ) -> Result<(AccountUpdate, RecoverySecrets)> {
        …
        // generate new keys for this recovery session
        let dkey = pke::DecryptionKey::gen(rng);

        // sign the recovery request with the signing key from RIK
        let sig = encap.key_sig.sign(
            rng,
            &RecoveryRequestMessage {
                account_id: acc,
                recovery_pke: dkey.encryption_key(),
            },
        );
        …
        Ok((
            update,
            RecoverySecrets {
                acc,
                rec: self.rec.clone(),
                msk_ss_rik: *encap.msk_ss_rik.as_bytes(),
                dkey,
            },
        ))
    }
}

GitHub permalink: lib/src/account/v0.rs#L165-L226 – AccountStateV0::initiate_recovery

  • The final reconstruction uses RecoverySecrets.dkey to decrypt the guardian shares:
impl RecoverySecrets {
    /// Complete recovery using guardian shares
    pub fn complete(&self, shares: &[GuardianShare]) -> Result<MasterSecretKey> {
        // recover the social secret share from the backup
        let msk_ss_social: MskSecretShareSocial = match &self.rec.social {
            BackupCiphertext::V0(v0) => {
                v0.recover(&self.dkey, &self.msk_ss_rik, &EmptyInfo, shares)?
            }
        };
        …
    }
}

GitHub permalink: lib/src/account/v0.rs#L140-L162 – RecoverySecrets::complete

During this recover call, each GuardianShare is:

  • Verified and decrypted, and
  • Discarded if decryption or commitment verification fails:
impl BackupCiphertextV0 {
    pub fn recover<M: Tagged + DeserializeOwned, A: Tagged>(
        &self,
        dke: &pke::DecryptionKey,
        sym: &sym::Key,
        aad: &A,
        shares: &[GuardianShare],
    ) -> Result<M, SwafeError> {
        // Verify and decrypt each share
        // Ignore invalid and duplicate shares
        let shares: Vec<(u32, Share)> = shares
            .iter()
            .filter_map(|share| {
                let GuardianShare::V0(share_v0) = share;
                let id = self.verify(share_v0).ok()?;
                let share: Share = dke.decrypt(&share_v0.ct, aad).ok()?;
                if self.comms[id as usize].hash == hash(&ShareHash { share: &share }) {
                    Some((id, share))
                } else {
                    None
                }
            })
            .collect::<BTreeMap<u32, Share>>()
            .into_iter()
            .collect();
        …
        if shares.len() < meta.threshold as usize {
            return Err(SwafeError::InsufficientShares);
        }
        …
    }
}

GitHub permalink: lib/src/backup/v0.rs#L289-L340 – BackupCiphertextV0::recover

Crucially, the on-chain storage for guardian shares does not encode which recovery session they belong to. The key used in the contract is only (account_id, backup_id, share_id). Any previously valid GuardianShare for that backup and guardian index will pass backup.verify, even if it was encrypted under a different, older recovery_pke from an earlier recovery attempt.

The combination of:

  1. Session-bound decryption (RecoverySecrets.dkey, per recovery attempt), and
  2. Session-agnostic storage (shares.insert(share_id, share) keyed only by backup + index),

means that stale shares from old recovery sessions remain verifiable but undecryptable in new recovery sessions.

Attack scenario and impact (Medium – Denial of Service)

Assuming an attacker can obtain previously uploaded guardian shares (e.g. via the unauthenticated /reconstruction/get-shares HTTP endpoint in contracts/src/http/endpoints/reconstruction/get_shares.rs, or through recorded network traffic/logs), the attacker can mount the following DoS:

Note: Even if the get-shares endpoint is restricted, any party that previously obtained guardian ciphertexts (e.g., by recording uploads) can replay them to overwrite fresh shares and deny recovery. A malicious guardian can already cause DoS by withholding; the replay/overwrite issue is impactful because a non‑guardian can block recovery despite all guardians cooperating.

  1. Recovery attempt 1 (Session 1)

    • User initiates recovery; a fresh recovery_pke₁ is published on-chain via AccountStateV0::initiate_recovery.
    • Guardians generate GuardianShares using send_for_recovery, encrypting shares under recovery_pke₁, and upload them via /reconstruction/upload-share.
    • Shares are stored under key (account_id, backup_id, share_id).
  2. Attacker collects session-1 shares

    • Because guardian shares are directly retrievable by any caller via /reconstruction/get-shares, an attacker can download the encoded GuardianShares for (account_id, backup_id).
  3. Recovery attempt 2 (Session 2)

    • Session 1 fails or is abandoned. The user initiates another recovery attempt.
    • AccountStateV0::initiate_recovery generates a fresh dkey₂ and publishes recovery_pke₂.
    • Guardians correctly compute new GuardianShares encrypted under recovery_pke₂ and upload them via /reconstruction/upload-share.
  4. Replay overwrite by attacker

    • Attacker replays the old session-1 GuardianShares by calling /reconstruction/upload-share with those stale ciphertexts.
    • The contract validates them with backup.verify (they are still cryptographically valid for the backup and index) and overwrites the fresh session-2 shares:

    [ \text{storedshare}[share*id] \gets \text{oldsharectunder }recovery*pke_1 ]

  5. Recovery fails (DoS)

    • When the user runs RecoverySecrets::complete(&shares) for session 2:
    • Decryption of stale shares under dkey₂ fails.
    • These shares are silently filtered out in BackupCiphertextV0::recover.
    • If enough shares have been overwritten, the number of successfully decrypted shares falls below the threshold, causing SwafeError::InsufficientShares.
    • The attacker can repeat this process indefinitely, repeatedly overwriting any new session-2 shares with old session-1 ciphertexts, effectively blocking the user from ever completing recovery for that backup, even though guardians cooperate.

This is a persistent Denial of Service against the recovery mechanism:

  • It does not enable key theft or account takeover (the attacker never learns the underlying Shamir shares or MSK).
  • It does allow an unauthenticated attacker (not just a guardian) to grief the user and permanently prevent successful recovery, as long as the attacker can continuously replay old shares.
  • Impact: blocks a critical user function (recovery of the master secret key for the account). For a user who has lost their keys, the inability to recover is effectively a loss of funds, but this is treated as Medium rather than High because it requires a prior failed recovery and active griefing.
  • Likelihood: realistic given public readability of shares and a simple replay pattern.
  • Not High, because there is no direct loss of funds or unauthorized control transfer, but it does materially affect user safety and recoverability.

Recommended mitigation steps

There are several complementary mitigation strategies; the most robust involves explicitly binding shares to recovery sessions.

  • Bind guardian shares to a specific recovery session (in the swafe_lib crate)

    In the swafe_lib crate, include a session identifier or epoch in the signed payload for guardian shares (e.g., augment the signed message such as SignedEncryptedShare).

    • Update the signing/types in swafe_lib (e.g., in lib/src/backup/v0.rs) to include the session_id (or a hash of the current recovery_pke) in the signed data.
    • Modify swafe_lib::backup::v0::BackupCiphertextV0::verify (or add a verify_for_session(...)) to enforce that a share’s session binding matches the active recovery session; old-session shares must not verify for a new session.
    • In upload_share, verify that the share’s session_id matches the current recovery session for that account.
    • If the session ID does not match, reject the upload.
    • This allows keeping the storage key as (account_id, backup_id, share_id) while ensuring that only shares for the active session are accepted. Since any valid share for the current session is functionally equivalent, overwrites within the same session are harmless (idempotent), but overwrites from old sessions are blocked.
  • Prevent or strictly control overwrites

    At minimum, make guardian shares append-only per session:

    • Reject an upload_share request if a share for (account_id, backup_id, session_id, share_id) already exists (where session_id is taken from the signed share metadata), unless the new payload is bitwise identical to the existing one.
    • Alternatively, allow overwrites only when accompanied by a nonce/timestamp and a guardian signature over (account_id, backup_id, session_id, share, timestamp), and store the latest timestamp; this makes replay of stale ciphertexts detectable and ignorable.
  • Optionally: restrict public readability or scope of get_shares

    The DoS described here heavily relies on an attacker being able to obtain old guardian shares:

    • Restrict /reconstruction/get-shares to authorized callers (e.g., require proof of control over the current recovery_pke or an authenticated session).
    • Or, at least, ensure it only returns shares from the latest session id and ignores/stops serving historical shares.

Implementing session-bound share storage and validation is the key mitigation: it ensures that old, but still cryptographically valid, guardian shares from previous recovery attempts cannot be replayed to corrupt the state of a new recovery session, thereby eliminating the observed DoS vector.

View detailed Proof of Concept

Swafe mitigated:

Bind guardian shares to recovery sessions via SessionId, preventing replay of shares across sessions

Status: Mitigation confirmed. Full details in reports from montecristo, niffylord, and DCENT09.


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

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 upload endpoint overwrote existing guardian shares keyed only by account, backup and share index, without binding shares to the current recovery session, so stale but still-verifiable shares from earlier sessions could replace fresh ones.

Impact

An unauthenticated attacker could persistently block recovery for a backup, preventing the user from recovering their master secret key, though no key theft or account takeover occurs.

What the attacker needed

Attacker can obtain old guardian shares; a prior failed or abandoned recovery; attacker can repeatedly replay uploads

The fix

Guardian shares should be bound to a recovery session identifier in the signed payload and verified against the current session on upload, rejecting stale shares; the project mitigated this by binding shares to sessions via a SessionId.

How it was found

  1. User starts recovery; a fresh recovery public key is published and guardians upload shares encrypted under it.
  2. Attacker obtains the session-1 guardian shares, for example via the get-shares endpoint.
  3. User starts a second recovery; guardians upload new shares encrypted under the new key.
  4. Attacker replays the old session-1 shares to the upload endpoint, which verifies and overwrites the fresh shares.
  5. Recovery fails because the stale shares cannot be decrypted under the new session key, leaving too few valid shares.

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.

When you lose your keys, guardians help you recover by sending encrypted pieces of a secret. Each recovery attempt uses a new encryption key, but the server stored the pieces without recording which attempt they belonged to. An attacker could resend old pieces, overwriting the new ones, so the user could never gather enough valid pieces to recover.

What is DoS?

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.

More from Swafe

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.