Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

214 improve detector for incorrect exponentiation and include new test cases #223

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions detectors/incorrect-exponentiation/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "incorrect-exponentiation"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
scout-audit-clippy-utils = { workspace = true }
dylint_linting = { workspace = true }
if_chain = { workspace = true }


[package.metadata.rust-analyzer]
rustc_private = true
89 changes: 89 additions & 0 deletions detectors/incorrect-exponentiation/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#![feature(rustc_private)]
#![warn(unused_extern_crates)]

extern crate rustc_hir;
extern crate rustc_span;

use rustc_hir::def_id::LocalDefId;
use rustc_hir::intravisit::Visitor;
use rustc_hir::intravisit::{walk_expr, FnKind};
use rustc_hir::{Body, FnDecl};
use rustc_hir::{Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_span::Span;
use scout_audit_clippy_utils::diagnostics::span_lint_and_help;

const LINT_MESSAGE: &str = "'^' It is not an exponential operator. It is a bitwise XOR.";
const LINT_HELP: &str = "If you want to use XOR, use bitxor(). If you want to raise a number use .checked_pow() or .pow() ";

dylint_linting::declare_late_lint! {
pub INCORRECT_EXPONENTIATION,
Warn,
LINT_MESSAGE,
{
name: "Incorrect Exponentiation",
long_message: LINT_MESSAGE,
severity: "Critical",
help: "https://coinfabrik.github.io/scout/docs/vulnerabilities/incorrect-exponentiation",
vulnerability_class: "Arithmetic",
}

}

impl<'tcx> LateLintPass<'tcx> for IncorrectExponentiation {
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
_: FnKind<'tcx>,
_: &'tcx FnDecl<'_>,
body: &'tcx Body<'_>,
_: Span,
_: LocalDefId,
) {
struct IncorrectExponentiationStorage {
span: Vec<Span>,
incorrect_exponentiation: bool,
}

impl<'tcx> Visitor<'tcx> for IncorrectExponentiationStorage {
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {

if let ExprKind::AssignOp(binop, _, _) = &expr.kind {
if binop.node == rustc_hir::BinOpKind::BitXor{
self.incorrect_exponentiation = true;
self.span.push(expr.span);
}
}

if let ExprKind::Binary(op, _, _) = &expr.kind {
if op.node == rustc_hir::BinOpKind::BitXor {
self.incorrect_exponentiation = true;
self.span.push(expr.span);
}
}

walk_expr(self, expr);
}
}

let mut expon_storage = IncorrectExponentiationStorage {
span: Vec::new(),
incorrect_exponentiation: false,
};

walk_expr(&mut expon_storage, body.value);

if expon_storage.incorrect_exponentiation {
for span in expon_storage.span.iter() {
span_lint_and_help(
cx,
INCORRECT_EXPONENTIATION,
*span,
LINT_MESSAGE,
None,
LINT_HELP,
);
}
}
}
}
18 changes: 18 additions & 0 deletions test-cases/incorrect-exponentiation/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[workspace]
exclude = [".cargo", "target"]
members = ["incorrect-exponentiation-*/*"]
resolver = "2"
[workspace.dependencies]
soroban-sdk = { version = "20.3.2" }
[profile.release]
codegen-units = 1
debug = 0
debug-assertions = false
lto = true
opt-level = "z"
overflow-checks = true
panic = "abort"
strip = "symbols"
[profile.release-with-logs]
debug-assertions = true
inherits = "release"
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "incorrect-exponentiation-remediated-1"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
soroban-sdk = { workspace = true }
[dev-dependencies]
soroban-sdk = { workspace = true, features = ["testutils"] }
[features]
testutils = ["soroban-sdk/testutils"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#![no_std]

use soroban_sdk::{contract, contractimpl,contracterror, contracttype, Env};

#[contracttype]
#[derive(Clone)]
enum DataKey {
Data,
}

// Agrega el atributo #[contracterror] a la definición de IEError
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum IEError {
CouldntRetrieveData = 1,
}

#[contract]
pub struct IncorrectExponentiation;

#[contractimpl]
impl IncorrectExponentiation {
pub fn set_data(e: Env, new_data: u128) {
e.storage()
.instance()
.set::<DataKey, u128>(&DataKey::Data, &new_data);
}

pub fn exp_data_3(e: Env) -> Result<u128, IEError> {
let data:Option<u128> = e.storage().instance().get(&DataKey::Data);
match data
{
Some(x) => return Ok(x.pow(3)),
None =>return Err(IEError::CouldntRetrieveData),
}
}
}

#[cfg(test)]
mod tests {
use soroban_sdk::{testutils, Address, Env};

use crate::{IncorrectExponentiation, IncorrectExponentiationClient};

#[test]
fn simple_test() {
let env = Env::default();
let contract_id = env.register_contract(None, IncorrectExponentiation);
let client = IncorrectExponentiationClient::new(&env, &contract_id);
env.mock_all_auths();
let _user = <Address as testutils::Address>::generate(&env);



client.set_data(&3_u128);

assert_eq!(client.exp_data_3(), 27);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "incorrect-exponentiation-vulnerable-1"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
soroban-sdk = { workspace = true }
[dev-dependencies]
soroban-sdk = { workspace = true, features = ["testutils"] }
[features]
testutils = ["soroban-sdk/testutils"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#![no_std]

use soroban_sdk::{contract, contractimpl,contracterror, contracttype, Env};

#[contracttype]
#[derive(Clone)]
enum DataKey {
Data,
}

// Agrega el atributo #[contracterror] a la definición de IEError
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum IEError {
CouldntRetrieveData = 1,
}

#[contract]
pub struct IncorrectExponentiation;

#[contractimpl]
impl IncorrectExponentiation {
pub fn set_data(e: Env, new_data: u128) {
e.storage()
.instance()
.set::<DataKey, u128>(&DataKey::Data, &new_data);
}

pub fn exp_data_3(e: Env) -> Result<u128, IEError> {
let data: Option<u128> = e.storage().instance().get(&DataKey::Data);
match data {
Some(mut x) => {
x ^= 3;
Ok(x)
},
None => Err(IEError::CouldntRetrieveData),
}
}

}

#[cfg(test)]
mod tests {
use soroban_sdk::{testutils, Address, Env};

use crate::{IncorrectExponentiation, IncorrectExponentiationClient};

#[test]
fn simple_test() {
let env = Env::default();
let contract_id = env.register_contract(None, IncorrectExponentiation);
let client = IncorrectExponentiationClient::new(&env, &contract_id);
env.mock_all_auths();
let _user = <Address as testutils::Address>::generate(&env);

client.set_data(&3_u128);

assert_ne!(client.exp_data_3(), 27);
}
}
Loading