Rust智能合约防御DoS攻击实战指南

Rust智能合约中的拒绝服务攻击

拒绝服务(DoS)攻击会使智能合约在一段时间内无法被正常使用。主要有以下几种原因:

  1. 合约逻辑中存在计算复杂度过高的缺陷,导致Gas消耗超出限制。

  2. 跨合约调用时,合约执行依赖不可靠的外部合约状态,造成阻塞。

  3. 合约所有者丢失私钥,导致关键的特权函数无法执行。

下面通过具体例子来分析这些DoS漏洞。

1. 遍历可被外部更改的大型数据结构

以下是一个简单的"分红"合约,存在DoS风险:

rust #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { pub registered: Vec, pub accounts: UnorderedMap<accountid, balance="">, }

pub fn register_account(&mut self) { if self.accounts.insert(&env::predecessor_account_id(), &0).is_some() { env::panic("The account is already registered".to_string().as_bytes()); } else { self.registered.push(env::predecessor_account_id()); } log!("Registered account {}", env::predecessor_account_id()); }

pub fn distribute_token(&mut self, amount: u128) { assert_eq!(env::predecessor_account_id(), DISTRIBUTOR, "ERR_NOT_ALLOWED");

for cur_account in self.registered.iter() {
    let balance = self.accounts.get(&cur_account).expect("ERR_GET");
    self.accounts.insert(&cur_account, &balance.checked_add(amount).expect("ERR_ADD"));
    log!("Try distribute to account {}", &cur_account);
    
    ext_ft_token::ft_transfer(
        cur_account.clone(),
        amount,
        &FTTOKEN,
        0,
        GAS_FOR_SINGLE_CALL  
    );
}

}

这里self.registered可被无限扩大,导致遍历时Gas不足。

应改用"提现"模式,让用户主动提取奖励:

rust pub fn withdraw(&mut self) { let account_id = env::predecessor_account_id(); let amount = self.accounts.get(&account_id).expect("No reward");

self.accounts.insert(&account_id, &0);

ext_ft_token::ft_transfer(
    account_id,
    amount, 
    &FTTOKEN,
    0,
    GAS_FOR_SINGLE_CALL
);

}

2. 跨合约状态依赖导致阻塞

以下是一个"竞价"合约:

rust #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { pub registered: Vec, pub bid_price: UnorderedMap<accountid, balance="">, pub current_leader: AccountId, pub highest_bid: u128, pub refund: bool }

pub fn bid(&mut self, sender_id: AccountId, amount: u128) -> PromiseOrValue { assert!(amount > self.highest_bid);

if self.current_leader == DEFAULT_ACCOUNT {
    self.current_leader = sender_id;
    self.highest_bid = amount;
} else {
    ext_ft_token::account_exist(
        self.current_leader.clone(),
        &FTTOKEN,
        0,
        env::prepaid_gas() - GAS_FOR_SINGLE_CALL * 4,
    ).then(ext_self::account_resolve(
        sender_id,
        amount,
        &env::current_account_id(),
        0,
        GAS_FOR_SINGLE_CALL * 3,
    ));
}

log!(
    "current_leader: {} highest_bid: {}",
    self.current_leader,
    self.highest_bid
);

PromiseOrValue::Value(0)

}

#[private] pub fn account_resolve(&mut self, sender_id: AccountId, amount: u128) { match env::promise_result(0) { PromiseResult::NotReady => unreachable!(), PromiseResult::Successful(_) => { ext_ft_token::ft_transfer( self.current_leader.clone(), self.highest_bid, &FTTOKEN, 0, GAS_FOR_SINGLE_CALL * 2, ); self.current_leader = sender_id; self.highest_bid = amount; } PromiseResult::Failed => { ext_ft_token::ft_transfer( sender_id.clone(), amount, &FTTOKEN, 0, GAS_FOR_SINGLE_CALL * 2, ); log!("Return Back Now"); } }; }

如果前一出价者账户被销毁,新的出价将被阻塞。

应考虑外部调用失败的情况,可以将无法退回的代币暂存,供用户后续提取:

rust pub fn withdraw_lost_funds(&mut self) { let account_id = env::predecessor_account_id(); let amount = self.lost_funds.get(&account_id).expect("No lost funds");

self.lost_funds.remove(&account_id);

ext_ft_token::ft_transfer(
    account_id,
    amount,
    &FTTOKEN,
    0,
    GAS_FOR_SINGLE_CALL
);

}

3. 所有者私钥丢失

某些关键函数只能由合约所有者调用。如果所有者丢失私钥,这些函数将无法执行。

应采用多签名方案来管理合约,避免单点故障:

rust pub struct MultiSigContract { owners: Vec, required_confirmations: u32, }

pub fn submit_transaction(&mut self, transaction: Transaction) { assert!(self.owners.contains(&env::predecessor_account_id())); // 添加交易到待确认列表 }

pub fn confirm_transaction(&mut self, transaction_id: u64) { assert!(self.owners.contains(&env::predecessor_account_id())); // 增加确认数 // 如果确认数达到要求,执行交易 }

通过以上方法可以有效防范智能合约中的DoS攻击风险。

</accountid,></accountid,>

此页面可能包含第三方内容,仅供参考(非陈述/保证),不应被视为 Gate 认可其观点表述,也不得被视为财务或专业建议。详见声明
  • 赞赏
  • 7
  • 分享
评论
0/400
ConsensusDissentervip
· 07-19 04:59
干货值得收藏学习
回复0
MEV猎手小张vip
· 07-18 23:52
不愧是经验之谈
回复0
PumpBeforeRugvip
· 07-18 15:28
Gas费谁买单了解下
回复0
GmGnSleepervip
· 07-17 00:43
安全至上没毛病
回复0
无常损失资深哲学家vip
· 07-17 00:41
强制重启就完事了
回复0
GasFeePhobiavip
· 07-17 00:23
Gas费是个大问题
回复0
All_InAlicevip
· 07-17 00:21
Gas优化很重要
回复0
交易,随时随地
qrCode
扫码下载 Gate APP
社群列表
简体中文
  • 简体中文
  • English
  • Tiếng Việt
  • 繁體中文
  • Español
  • Русский
  • Français (Afrique)
  • Português (Portugal)
  • Bahasa Indonesia
  • 日本語
  • بالعربية
  • Українська
  • Português (Brasil)