Skip to content

Commit

Permalink
Detector: constant functions contains assembly (#641)
Browse files Browse the repository at this point in the history
Co-authored-by: Alex Roan <[email protected]>
  • Loading branch information
TilakMaddy and alexroan authored Aug 5, 2024
1 parent 155a9d6 commit ada7f0f
Show file tree
Hide file tree
Showing 8 changed files with 399 additions and 15 deletions.
5 changes: 5 additions & 0 deletions aderyn_core/src/detect/detector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ pub fn get_all_issue_detectors() -> Vec<Box<dyn IssueDetector>> {
Box::<WeakRandomnessDetector>::default(),
Box::<PreDeclaredLocalVariableUsageDetector>::default(),
Box::<DeletionNestedMappingDetector>::default(),
Box::<ConstantFunctionContainsAssemblyDetector>::default(),
Box::<BooleanEqualityDetector>::default(),
Box::<TxOriginUsedForAuthDetector>::default(),
Box::<MsgValueUsedInLoopDetector>::default(),
Expand Down Expand Up @@ -148,6 +149,7 @@ pub(crate) enum IssueDetectorNamePool {
WeakRandomness,
PreDeclaredLocalVariableUsage,
DeleteNestedMapping,
ConstantFunctionsAssembly,
BooleanEquality,
TxOriginUsedForAuth,
MsgValueInLoop,
Expand Down Expand Up @@ -310,6 +312,9 @@ pub fn request_issue_detector_by_name(detector_name: &str) -> Option<Box<dyn Iss
IssueDetectorNamePool::DeleteNestedMapping => {
Some(Box::<DeletionNestedMappingDetector>::default())
}
IssueDetectorNamePool::ConstantFunctionsAssembly => {
Some(Box::<ConstantFunctionContainsAssemblyDetector>::default())
}
IssueDetectorNamePool::BooleanEquality => Some(Box::<BooleanEqualityDetector>::default()),
IssueDetectorNamePool::TxOriginUsedForAuth => {
Some(Box::<TxOriginUsedForAuthDetector>::default())
Expand Down
166 changes: 166 additions & 0 deletions aderyn_core/src/detect/low/constant_funcs_assembly.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
use std::collections::BTreeMap;
use std::error::Error;
use std::str::FromStr;

use crate::ast::{ASTNode, NodeID, NodeType, StateMutability};

use crate::capture;
use crate::context::browser::{
ExtractInlineAssemblys, ExtractPragmaDirectives, GetClosestAncestorOfTypeX,
};
use crate::context::investigator::{
StandardInvestigationStyle, StandardInvestigator, StandardInvestigatorVisitor,
};
use crate::detect::detector::IssueDetectorNamePool;
use crate::detect::helpers::{self, pragma_directive_to_semver};
use crate::{
context::workspace_context::WorkspaceContext,
detect::detector::{IssueDetector, IssueSeverity},
};
use eyre::Result;
use semver::{Version, VersionReq};

#[derive(Default)]
pub struct ConstantFunctionContainsAssemblyDetector {
// Keys are: [0] source file name, [1] line number, [2] character location of node.
// Do not add items manually, use `capture!` to add nodes to this BTreeMap.
found_instances: BTreeMap<(String, usize, String), NodeID>,
}

impl IssueDetector for ConstantFunctionContainsAssemblyDetector {
fn detect(&mut self, context: &WorkspaceContext) -> Result<bool, Box<dyn Error>> {
for function in helpers::get_implemented_external_and_public_functions(context) {
// First, check the eligibility for this function by checking
if let Some(ASTNode::SourceUnit(source_unit)) =
function.closest_ancestor_of_type(context, NodeType::SourceUnit)
{
// Store the extracted directives in a variable to extend its lifetime
let extracted_directives = ExtractPragmaDirectives::from(source_unit).extracted;
let pragma_directive = extracted_directives.first();

if let Some(pragma_directive) = pragma_directive {
let version_req = pragma_directive_to_semver(pragma_directive);
if let Ok(version_req) = version_req {
if version_req_allows_below_0_5_0(&version_req) {
// Only run the logic if pragma is allowed to run on solc <0.5.0

if function.state_mutability() == &StateMutability::View
|| function.state_mutability() == &StateMutability::Pure
{
let mut tracker = AssemblyTracker {
has_assembly: false,
};
let investigator = StandardInvestigator::new(
context,
&[&(function.into())],
StandardInvestigationStyle::Downstream,
)?;
investigator.investigate(context, &mut tracker)?;

if tracker.has_assembly {
capture!(self, context, function);
}
}
}
}
}
}
}

Ok(!self.found_instances.is_empty())
}

fn severity(&self) -> IssueSeverity {
IssueSeverity::Low
}

fn title(&self) -> String {
String::from("Functions declared `pure` / `view` but contains assembly")
}

fn description(&self) -> String {
String::from("If the assembly code contains bugs or unintended side effects, it can lead to incorrect results \
or vulnerabilities, which are hard to debug and resolve, especially when the function is meant to be simple \
and predictable.")
}

fn instances(&self) -> BTreeMap<(String, usize, String), NodeID> {
self.found_instances.clone()
}

fn name(&self) -> String {
format!("{}", IssueDetectorNamePool::ConstantFunctionsAssembly)
}
}

fn version_req_allows_below_0_5_0(version_req: &VersionReq) -> bool {
// If it matches any 0.4.0 to 0.4.26, return true
for i in 0..=26 {
let version: semver::Version = Version::from_str(&format!("0.4.{}", i)).unwrap();
if version_req.matches(&version) {
return true;
}
}

// Else, return false
false
}

struct AssemblyTracker {
has_assembly: bool,
}

impl StandardInvestigatorVisitor for AssemblyTracker {
fn visit_any(&mut self, node: &crate::ast::ASTNode) -> eyre::Result<()> {
// If we are already satisifed, do not bother checking
if self.has_assembly {
return Ok(());
}

if let ASTNode::FunctionDefinition(function) = node {
// Ignore checking functions that start with `_`
// Example - templegold contains math functions like `_rpow()`, etc that are used by view functions
// That should be okay .. I guess? (idk ... it's open for dicussion)
if function.name.starts_with("_") {
return Ok(());
}
}

// Check if this node has assembly code
let assemblies = ExtractInlineAssemblys::from(node).extracted;
if !assemblies.is_empty() {
self.has_assembly = true;
}
Ok(())
}
}

#[cfg(test)]
mod constant_functions_assembly_detector {
use serial_test::serial;

use crate::detect::{
detector::IssueDetector,
low::constant_funcs_assembly::ConstantFunctionContainsAssemblyDetector,
};

#[test]
#[serial]
fn test_constant_functions_assembly() {
let context = crate::detect::test_utils::load_solidity_source_unit(
"../tests/contract-playground/src/ConstantFuncsAssembly.sol",
);

let mut detector = ConstantFunctionContainsAssemblyDetector::default();
let found = detector.detect(&context).unwrap();
// assert that the detector found an issue
assert!(found);
// assert that the detector found the correct number of instances
assert_eq!(detector.instances().len(), 3);
// assert the severity is low
assert_eq!(
detector.severity(),
crate::detect::detector::IssueSeverity::Low
);
}
}
2 changes: 2 additions & 0 deletions aderyn_core/src/detect/low/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub(crate) mod boolean_equality;
pub(crate) mod centralization_risk;
pub(crate) mod constant_funcs_assembly;
pub(crate) mod constants_instead_of_literals;
pub(crate) mod contracts_with_todos;
pub(crate) mod deprecated_oz_functions;
Expand Down Expand Up @@ -27,6 +28,7 @@ pub(crate) mod zero_address_check;

pub use boolean_equality::BooleanEqualityDetector;
pub use centralization_risk::CentralizationRiskDetector;
pub use constant_funcs_assembly::ConstantFunctionContainsAssemblyDetector;
pub use constants_instead_of_literals::ConstantsInsteadOfLiteralsDetector;
pub use contracts_with_todos::ContractsWithTodosDetector;
pub use deprecated_oz_functions::DeprecatedOZFunctionsDetector;
Expand Down
6 changes: 3 additions & 3 deletions cli/reportgen.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

#### MARKDOWN REPORTS ######

# Basic report.md
# Basic report.md
cargo run -- -i src/ -x lib/ ./tests/contract-playground -o ./reports/report.md --skip-update-check &

# Adhoc sol files report.md
# Adhoc sol files report.md
cargo run -- ./tests/adhoc-sol-files -o ./reports/adhoc-sol-files-report.md --skip-update-check &

# Aderyn.toml with nested root
Expand Down Expand Up @@ -41,4 +41,4 @@ cargo run -- ./tests/adhoc-sol-files -o ./reports/adhoc-sol-files-highs-only-re
# Basic report.sarif
cargo run -- ./tests/contract-playground -o ./reports/report.sarif --skip-update-check &

wait
wait
54 changes: 51 additions & 3 deletions reports/report.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"files_summary": {
"total_source_units": 78,
"total_sloc": 2252
"total_source_units": 79,
"total_sloc": 2278
},
"files_details": {
"files_details": [
Expand Down Expand Up @@ -37,6 +37,10 @@
"file_path": "src/CompilerBugStorageSignedIntegerArray.sol",
"n_sloc": 13
},
{
"file_path": "src/ConstantFuncsAssembly.sol",
"n_sloc": 26
},
{
"file_path": "src/ConstantsLiterals.sol",
"n_sloc": 28
Expand Down Expand Up @@ -321,7 +325,7 @@
},
"issue_count": {
"high": 36,
"low": 26
"low": 27
},
"high_issues": {
"issues": [
Expand Down Expand Up @@ -1287,6 +1291,12 @@
"src": "97:1",
"src_char": "97:1"
},
{
"contract_path": "src/ConstantFuncsAssembly.sol",
"line_no": 6,
"src": "110:20",
"src_char": "110:20"
},
{
"contract_path": "src/DelegateCallWithoutAddressCheck.sol",
"line_no": 9,
Expand Down Expand Up @@ -2205,6 +2215,12 @@
"src": "32:23",
"src_char": "32:23"
},
{
"contract_path": "src/ConstantFuncsAssembly.sol",
"line_no": 2,
"src": "32:23",
"src_char": "32:23"
},
{
"contract_path": "src/ContractLocksEther.sol",
"line_no": 2,
Expand Down Expand Up @@ -3711,6 +3727,12 @@
"src": "1206:18",
"src_char": "1206:18"
},
{
"contract_path": "src/ConstantFuncsAssembly.sol",
"line_no": 26,
"src": "651:232",
"src_char": "651:232"
},
{
"contract_path": "src/InternalFunctions.sol",
"line_no": 28,
Expand Down Expand Up @@ -4080,6 +4102,31 @@
}
]
},
{
"title": "Functions declared `pure` / `view` but contains assembly",
"description": "If the assembly code contains bugs or unintended side effects, it can lead to incorrect results or vulnerabilities, which are hard to debug and resolve, especially when the function is meant to be simple and predictable.",
"detector_name": "constant-functions-assembly",
"instances": [
{
"contract_path": "src/ConstantFuncsAssembly.sol",
"line_no": 9,
"src": "182:175",
"src_char": "182:175"
},
{
"contract_path": "src/ConstantFuncsAssembly.sol",
"line_no": 17,
"src": "408:237",
"src_char": "408:237"
},
{
"contract_path": "src/ConstantFuncsAssembly.sol",
"line_no": 36,
"src": "934:98",
"src_char": "934:98"
}
]
},
{
"title": "Boolean equality is not required.",
"description": "If `x` is a boolean, there is no need to do `if(x == true)` or `if(x == false)`. Just use `if(x)` and `if(!x)` respectively.",
Expand Down Expand Up @@ -4172,6 +4219,7 @@
"weak-randomness",
"pre-declared-local-variable-usage",
"delete-nested-mapping",
"constant-functions-assembly",
"boolean-equality",
"tx-origin-used-for-auth",
"msg-value-in-loop",
Expand Down
Loading

0 comments on commit ada7f0f

Please sign in to comment.