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

167 add new detector and test cases for incorrect exponentiation #215

Closed
Show file tree
Hide file tree
Changes from 9 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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Currently Scout includes the following detectors.
| [unrestricted-transfer-from](https://github.com/CoinFabrik/scout-soroban/tree/main/detectors/unrestricted-transfer-from) | Avoid passing an user-defined parameter as a `from` field in transfer-from. | [1](https://github.com/CoinFabrik/scout-soroban/tree/main/test-cases/unrestricted-transfer-from/unrestricted-transfer-from-1) | Critical |
| [unsafe-map-get](https://github.com/CoinFabrik/scout-soroban/tree/main/detectors/unsafe-map-get) | Inappropriate usage of the `get` method for `Map` in soroban | [1](https://github.com/CoinFabrik/scout-soroban/tree/main/test-cases/unsafe-map-get/unsafe-map-get-1) | Medium |
| [zero-or-test-address](https://github.com/CoinFabrik/scout-soroban/tree/main/detectors/zero-or-test-address) | Avoid zero or test address assignment to prevent contract control loss. | [1](https://github.com/CoinFabrik/scout-soroban/tree/main/test-cases/zero-or-test-address/zero-or-test-address-1) | Validations and error handling |
| [incorrect-exponentation](https://github.com/CoinFabrik/scout-soroban/tree/main/detectors/incorrect-exponentiation) | Warns against incorrect usage of ´^´. | [1](https://github.com/CoinFabrik/scout-soroban/tree/main/test-cases/incorrect-exponentiation/incorrect-exponentiation-1) | Critical |

## Output formats

Expand Down Expand Up @@ -133,3 +134,4 @@ Our team has an academic background in computer science and mathematics, with wo
## License

Scout is licensed and distributed under a MIT license. [Contact us](https://www.coinfabrik.com/) if you're looking for an exception to the terms.

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
81 changes: 81 additions & 0 deletions detectors/incorrect-exponentiation/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#![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::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,
);
}
}
}
}
43 changes: 43 additions & 0 deletions docs/docs/detectors/21-incorrect-exponentiation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Zero or test address

### What it does
Checks whether the zero address is being inputed to a function without validation.

### Why is this bad?
Because the private key for the zero address is known, anyone could take ownership of the contract.

### Example

```rust
pub fn set(e: Env, admin: Address, data: i32) -> Result<(), Error> {
if !ZeroAddressContract::ensure_is_admin(&e, admin)? {
return Err(Error::NotAdmin);
}
e.storage().persistent().set(&DataKey::Data, &data);
Ok(())
}
```


Use instead:
```rust
pub fn set(e: Env, admin: Address, data: i32) -> Result<(), Error> {
if admin
== Address::from_string(&String::from_bytes(
&e,
b"GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
))
{
return Err(Error::InvalidNewAdmin);
}
if !ZeroAddressContract::ensure_is_admin(&e, admin)? {
return Err(Error::NotAdmin);
}
e.storage().persistent().set(&DataKey::Data, &data);
Ok(())
}
```

### Implementation

The detector's implementation can be found at [this link](https://github.com/CoinFabrik/scout-soroban/tree/main/detectors/zero-or-test-address).
51 changes: 51 additions & 0 deletions docs/docs/vulnerabilities/21-incorrect-exponentiation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Incorrect Exponentiation

## Description

- Vulnerability Category: `Arithmetic`
- Vulnerability Severity: `Critical`
- Detectors: [`incorrect-exponentiation`](https://github.com/CoinFabrik/scout-soroban/tree/main/detectors/incorrect-exponentiation)
- Test Cases: [`incorrect-exponentiation-1`](https://github.com/CoinFabrik/scout-soroban/tree/main/test-cases/incorrect-exponentiation/incorrect-exponentiation-1)


The operator `^` is not an exponential operator, it is a bitwise XOR. Make sure to use `pow()` instead for exponentiation. In case of performing a XOR operation, use `.bitxor()` for clarity.

## Exploit Scenario

In the following example, the `^` operand is being used for exponentiation. But in Rust, `^` is the operand for an XOR operation. If misused, this could lead to unexpected behaviour in our contract.

```rust
pub fn exp_data_3(e: Env) -> u128 {
let mut data = e.storage()
.instance()
.get::<DataKey, u128>(&DataKey::Data)
.expect("Data not found");

data = data ^ 3;
return data;
}
```

The vulnerable code example can be found [`here`](https://github.com/CoinFabrik/scout-soroban/tree/main/test-cases/incorrect-exponentiation/incorrect-exponentiation-1/vulnerable-example).

## Remediation

A possible solution is to use the method `pow()`. But, if a XOR operation is wanted, `.bitxor()` method is recommended.

```rust
pub fn exp_data_3(e: Env) -> u128 {
let data = e.storage()
.instance()
.get::<DataKey, u128>(&DataKey::Data)
.expect("Data not found");

return data.pow(3);
}
```

The remediated code example can be found [`here`](https://github.com/CoinFabrik/scout-soroban/tree/main/test-cases/incorrect-exponentiation/incorrect-exponentiation-1/remediated-example).

## References

- https://doc.rust-lang.org/std/ops/trait.BitXor.html

6 changes: 6 additions & 0 deletions docs/docs/vulnerabilities/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,3 +257,9 @@ Assigning a test address can also have similar implications, including the loss

This vulnerability falls under the [Validations and error handling](#vulnerability-categories) category
and has a Medium severity.

### Incorrect Exponentiation

It's common to use `^` for exponentiation. However in Rust, `^` is the XOR operator. If the `^` operator is used, it could lead to unexpected behavior in the contract. It's recommended to use the method `pow()` for exponentiation or `.bitxor()` for XOR operations.

This vulnerability falls under the [Arithmetic](#vulnerability-categories) category and has a Critical severity.
22 changes: 22 additions & 0 deletions test-cases/incorrect-exponentiation/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[workspace]
exclude = [".cargo", "target"]
members = ["incorrect-exponentiation-*/*"]
resolver = "2"

[workspace.dependencies]
soroban-sdk = "20.3.2"

[profile.release]
opt-level = "z"
overflow-checks = true
debug = 0
strip = "symbols"
debug-assertions = false
panic = "abort"
codegen-units = 1
lto = true

# For more information about this profile see https://soroban.stellar.org/docs/basic-tutorials/logging#cargotoml-profile
[profile.release-with-logs]
inherits = "release"
debug-assertions = true
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "incorrect-exponentiation-remediated-1"
version = "0.0.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,62 @@
#![no_std]

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

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

#[contract]
pub struct IncorrectExponentiation;

#[contractimpl]
impl IncorrectExponentiation {

pub fn init(e: Env){
e.storage()
.instance()
.set::<DataKey, u128>(&DataKey::Data, &(255_u128.pow(2) - 1));
}

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) -> u128 {
let data = e.storage()
.instance()
.get::<DataKey, u128>(&DataKey::Data)
.expect("Data not found");

data.pow(3)
}

}

#[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.init();
client.set_data(&10_u128);

assert_eq!(client.exp_data_3(), 1000);
}
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "incorrect-exponentiation-vulnerable-1"
version = "0.0.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"]
Loading
Loading