Anchor 中的 init_if_needed 与重新初始化攻击防范

  • 0xE
  • 发布于 1天前
  • 阅读 233

本文介绍了 Anchor 中 init_if_needed 宏的用法,分析了其简化账户初始化的优势,同时探讨了重新初始化攻击的风险,并提出了通过单一初始化和限制操作等防护措施来确保程序安全性的建议。

在之前的 Solana 教程中,账户需先通过单独事务初始化才能写入数据。为简化操作,Anchor 提供了 init_if_needed 宏,允许在单次事务中初始化并操作账户。本文将探讨其用法、潜在的重新初始化攻击风险及防护措施。


init_if_needed 示例

以下计数器程序无需独立初始化,直接递增计数。

Rust 实现

use anchor_lang::prelude::*;
use std::mem::size_of;

declare_id!("BryuGUGr6sYHmG7w6BmLmTCM7kmZjNKRXXEDWkiahUAP");

#[program]
pub mod init_if_needed {
    use super::*;

    pub fn increment(ctx: Context<Initialize>) -> Result<()> {
        let current_counter = ctx.accounts.my_pda.counter;
        ctx.accounts.my_pda.counter = current_counter + 1;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(
        init_if_needed,
        payer = signer,
        space = size_of::<MyPDA>() + 8,
        seeds = [],
        bump
    )]
    pub my_pda: Account<'info, MyPDA>,

    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct MyPDA {
    pub counter: u64,
}

Typescript 测试

import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { InitIfNeeded } from "../target/types/init_if_needed";

describe("init_if_needed", () => {
  // Configure the client to use the local cluster.
  anchor.setProvider(anchor.AnchorProvider.env());

  const program = anchor.workspace.InitIfNeeded as Program<InitIfNeeded>;

  it("Is initialized!", async () => {
    const [myPda, _bump] = anchor.web3.PublicKey.findProgramAddressSync([], program.programId);
    await program.methods.increment().accounts({myPda: myPda}).rpc();
    await program.methods.increment().accounts({myPda: myPda}).rpc();
    await program.methods.increment().accounts({myPda: myPda}).rpc();

    let result = await program.account.myPda.fetch(myPda);
    console.log(`counter is ${result.counter}`);
  });
});

构建错误

运行 anchor build 时,报错:

error: init_if_needed requires that anchor-lang be imported with the init-if-needed cargo feature enabled. Carefully read the init_if_needed docs before using this feature to make sure you know how to protect yourself against re-initialization attacks.
  --> programs/init_if_needed/src/lib.rs:20:9
   |
20 |         init_if_needed,
   |

解决方法:在 Cargo.toml 中启用特性:

[dependencies]
anchor-lang = { version = "0.29.0", features = ["init-if-needed"] }

但在使用前,需理解重新初始化攻击的风险。


默认初始化限制

Anchor 默认禁止账户重复初始化,若尝试初始化已存在账户,事务失败。

Anchor 的初始化判定

  • 未初始化:账户 lamports 余额为 0 或所有者为系统程序(111...111)。
  • 已初始化:账户由程序拥有且 lamports 非零。

验证示例

以下程序展示初始化限制及潜在漏洞:

Rust 实现

use anchor_lang::prelude::*;
use anchor_lang::system_program;
use std::mem::size_of;

declare_id!("43CvSmeND3dwybVMNsi3TVrrnAFvfxaXq1bXMuVsszGh");

#[program]
pub mod reinit_attack {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        Ok(())
    }

    pub fn drain_lamports(ctx: Context<DrainLamports>) -> Result<()> {
        let lamports = ctx.accounts.my_pda.to_account_info().lamports();
        ctx.accounts.my_pda.sub_lamports(lamports)?;
        ctx.accounts.signer.add_lamports(lamports)?;
        Ok(())
    }

    pub fn give_to_system_program(ctx: Context<GiveToSystemProgram>) -> Result<()> {
        let account_info = &mut ctx.accounts.my_pda.to_account_info();
        // the assign method changes the owner
        account_info.assign(&system_program::ID);
        account_info.realloc(0, false)?;

        Ok(())
    }
}

#[derive(Accounts)]
pub struct DrainLamports<'info> {
    #[account(mut)]
    pub my_pda: Account<'info, MyPDA>,
    #[account(mut)]
    pub signer: Signer<'info>,
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(init, payer = signer, space = 8, seeds = [], bump)]
    pub my_pda: Account<'info, MyPDA>,

    #[account(mut)]
    pub signer: Signer<'info>,

    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct GiveToSystemProgram<'info> {
    #[account(mut)]
    pub my_pda: Account<'info, MyPDA>,
}

#[account]
pub struct MyPDA {}

Typescript 测试

import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { ReinitAttack } from "../target/types/reinit_attack";

describe("Program", () => {
  anchor.setProvider(anchor.AnchorProvider.env());

  const program = anchor.workspace.ReinitAttack as Program<ReinitAttack>;

  it("initialize after giving to system program or draining lamports", async () => {
    const [myPda, _bump] = anchor.web3.PublicKey.findProgramAddressSync([], program.programId);

    await program.methods.initialize().accounts({myPda: myPda}).rpc();

    await program.methods.giveToSystemProgram().accounts({myPda: myPda}).rpc();

    await program.methods.initialize().accounts({myPda: myPda}).rpc();
    console.log("account initialized after giving to system program!");

    await program.methods.drainLamports().accounts({myPda: myPda}).rpc();

    await program.methods.initialize().accounts({myPda: myPda}).rpc();
    console.log("account initialized after draining lamports!");
  });
});

执行流程

  1. 初始化 PDA。
  2. 将所有权转移给系统程序。
  3. 再次初始化成功。
  4. 清空 lamports。
  5. lamports 为零时,账户被视为不存在。
  6. 再次初始化成功。

结论

Solana 无“已初始化”标志,Anchor 依赖所有权和 lamports 判断。若账户归系统程序或余额为零,可被重新初始化。


重新初始化的风险

计数器示例的风险

  • 转移所有权:清空数据后,计数器可重置。
  • 清空 lamports:余额为零后,账户可重置。
  • 业务逻辑:若计数器不应重置,可能导致错误。

Anchor 通过特性标志提醒开发者评估这种风险。

防护建议

  • 单一初始化:使用 init 并添加检查(如布尔标志)。
  • 限制操作:避免提供 drain_lamports 或 give_to_system_program。

双初始化路径的隐患

在计数器示例中,init_if_needed 使初值为 1。若另有 init 函数设初值为 0,可能导致逻辑不一致。

与以太坊对比

  • 以太坊:未触及的存储变量默认为 0。
  • Solana:未初始化账户不存在,无法读取。

清空数据的影响

清空账户数据不影响初始化状态。

Rust 实现

use anchor_lang::prelude::*;
use std::mem::size_of;
use anchor_lang::system_program;

declare_id!("FC467mPCCKXG97ut1WdLLi55vuAcyCW8AD1vid27bZfn");

#[program]
pub mod reinit_attack {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
        Ok(())
    }

    pub fn erase(ctx: Context<Erase>) -> Result<()> {
        ctx.accounts.my_pda.realloc(0, false)?;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Erase<'info> {
    /// CHECK: We are going to erase the account
    #[account(mut)]
    pub my_pda: UncheckedAccount<'info>,
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(init, payer = signer, space = 8, seeds = [], bump)]
    pub my_pda: Account<'info, MyPDA>,

    #[account(mut)]
    pub signer: Signer<'info>,

    pub system_program: Program<'info, System>,
}

#[account]
pub struct MyPDA {}

验证

  • 初始化后,erase 清空数据。
  • 再次初始化将失败,因所有权和 lamports 未变。

总结

init_if_needed 简化账户初始化,但需警惕:

  • 重新初始化:lamports 为零或所有权归系统程序时可能发生。
  • 双路径风险:多种初始化方式可能导致状态不一致。
  • 数据清空:不影响初始化状态。
  • 盲目写入:若程序包含无条件写入账户的函数,则可能覆盖现有数据。擦除方法需要使用 UncheckedAccount 来加载帐户。

开发者应根据业务需求选择 init 或 init_if_needed,并设计防护机制。


【笔记配套代码】 https://github.com/0xE1337/rareskills_evm_to_solana 【参考资料】 https://learnblockchain.cn/column/119 https://www.rareskills.io/solana-tutorial

点赞 0
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
0xE
0xE
0x59f6...a17e
17年进入币圈,Web3 开发者。刨根问底探链上真相,品味坎坷悟 Web3 人生。