Skip to content

Commit

Permalink
Detector: Weak Randomness (#618)
Browse files Browse the repository at this point in the history
Co-authored-by: Alex Roan <[email protected]>
  • Loading branch information
DavidDrob and alexroan authored Jul 28, 2024
1 parent fc3d760 commit c9c251d
Show file tree
Hide file tree
Showing 9 changed files with 640 additions and 16 deletions.
3 changes: 3 additions & 0 deletions aderyn_core/src/detect/detector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ pub fn get_all_issue_detectors() -> Vec<Box<dyn IssueDetector>> {
Box::<RTLODetector>::default(),
Box::<UncheckedReturnDetector>::default(),
Box::<DangerousUnaryOperatorDetector>::default(),
Box::<WeakRandomnessDetector>::default(),
Box::<PreDeclaredLocalVariableUsageDetector>::default(),
Box::<DeletionNestedMappingDetector>::default(),
]
Expand Down Expand Up @@ -128,6 +129,7 @@ pub(crate) enum IssueDetectorNamePool {
RTLO,
UncheckedReturn,
DangerousUnaryOperator,
WeakRandomness,
PreDeclaredLocalVariableUsage,
DeleteNestedMapping,
// NOTE: `Undecided` will be the default name (for new bots).
Expand Down Expand Up @@ -265,6 +267,7 @@ pub fn request_issue_detector_by_name(detector_name: &str) -> Option<Box<dyn Iss
IssueDetectorNamePool::DangerousUnaryOperator => {
Some(Box::<DangerousUnaryOperatorDetector>::default())
}
IssueDetectorNamePool::WeakRandomness => Some(Box::<WeakRandomnessDetector>::default()),
IssueDetectorNamePool::PreDeclaredLocalVariableUsage => {
Some(Box::<PreDeclaredLocalVariableUsageDetector>::default())
}
Expand Down
2 changes: 2 additions & 0 deletions aderyn_core/src/detect/high/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub(crate) mod unchecked_return;
pub(crate) mod uninitialized_state_variable;
pub(crate) mod unprotected_init_function;
pub(crate) mod unsafe_casting;
pub(crate) mod weak_randomness;
pub(crate) mod yul_return;

pub use arbitrary_transfer_from::ArbitraryTransferFromDetector;
Expand Down Expand Up @@ -54,4 +55,5 @@ pub use unchecked_return::UncheckedReturnDetector;
pub use uninitialized_state_variable::UninitializedStateVariableDetector;
pub use unprotected_init_function::UnprotectedInitializerDetector;
pub use unsafe_casting::UnsafeCastingDetector;
pub use weak_randomness::WeakRandomnessDetector;
pub use yul_return::YulReturnDetector;
190 changes: 190 additions & 0 deletions aderyn_core/src/detect/high/weak_randomness.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
use std::collections::BTreeMap;
use std::error::Error;

use crate::ast::{Expression, FunctionCall, FunctionCallKind, NodeID};

use crate::capture;
use crate::detect::detector::IssueDetectorNamePool;
use crate::{
context::workspace_context::{ASTNode, WorkspaceContext},
detect::detector::{IssueDetector, IssueSeverity},
};
use eyre::Result;

#[derive(Default)]
pub struct WeakRandomnessDetector {
// 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 WeakRandomnessDetector {
fn detect(&mut self, context: &WorkspaceContext) -> Result<bool, Box<dyn Error>> {
let keccaks: Vec<&FunctionCall> = context.function_calls()
.into_iter()
.filter(|x| matches!(*x.expression, Expression::Identifier(ref id) if id.name == "keccak256"))
.collect();

for keccak in keccaks {
// keccak256 must have exactly one argument
if let Some(arg) = keccak.arguments.first() {
if let Expression::FunctionCall(ref function_call) = *arg {
if check_encode(function_call) {
capture!(self, context, keccak);
}
}
// get variable definition
else if let Expression::Identifier(ref i) = *arg {
if let Some(node_id) = i.referenced_declaration {
let decleration = context.get_parent(node_id);

if let Some(ASTNode::VariableDeclarationStatement(var)) = decleration {
if let Some(Expression::FunctionCall(function_call)) =
&var.initial_value
{
if check_encode(function_call) {
capture!(self, context, keccak);
}
}
}
}
}
}
}

// check for modulo operations on block.timestamp, block.number and blockhash
for binary_operation in context
.binary_operations()
.into_iter()
.filter(|b| b.operator == "%")
{
// if left operand is a variable, get its definition and perform check
if let Expression::Identifier(ref i) = *binary_operation.left_expression {
if let Some(node_id) = i.referenced_declaration {
let decleration = context.get_parent(node_id);

if let Some(ASTNode::VariableDeclarationStatement(var)) = decleration {
if let Some(expression) = &var.initial_value {
if check_operand(expression) {
capture!(self, context, binary_operation);
continue;
}
}
}
}
}
// otherwise perform check directly on the expression
else if check_operand(&binary_operation.left_expression) {
capture!(self, context, binary_operation);
}
}

// check if contract uses block.prevrandao
for member_access in context.member_accesses() {
if member_access.member_name == "prevrandao"
&& matches!(*member_access.expression, Expression::Identifier(ref id) if id.name == "block")
{
capture!(self, context, member_access);
}
}

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

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

fn title(&self) -> String {
String::from("Weak Randomness")
}

fn description(&self) -> String {
String::from("The use of keccak256 hash functions on predictable values like block.timestamp, block.number, or similar data, including modulo operations on these values, should be avoided for generating randomness, as they are easily predictable and manipulable. The `PREVRANDAO` opcode also should not be used as a source of randomness. Instead, utilize Chainlink VRF for cryptographically secure and provably random values to ensure protocol integrity.")
}

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

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

// returns whether block.timestamp or block.number is used in encode function
fn check_encode(function_call: &FunctionCall) -> bool {
if let Expression::MemberAccess(ref member_access) = *function_call.expression {
if member_access.member_name == "encodePacked" || member_access.member_name == "encode" {
for argument in &function_call.arguments {
if let Expression::MemberAccess(ref member_access) = *argument {
if ["timestamp", "number"].iter().any(|ma| {
ma == &member_access.member_name &&
matches!(*member_access.expression, Expression::Identifier(ref id) if id.name == "block")
}) {
return true;
}
}
}
}
}
false
}

// returns whether operand is dependent on block.timestamp, block.number or blockhash
fn check_operand(operand: &Expression) -> bool {
match operand {
Expression::MemberAccess(member_access) => {
if ["timestamp", "number"].iter().any(|ma| {
ma == &member_access.member_name &&
matches!(*member_access.expression, Expression::Identifier(ref id) if id.name == "block")
}) {
return true;
}
},
Expression::FunctionCall(function_call) => {
if function_call.kind == FunctionCallKind::TypeConversion {
// type conversion must have exactly one argument
if let Some(Expression::FunctionCall(ref inner_function_call)) = function_call.arguments.first() {
if matches!(*inner_function_call.expression, Expression::Identifier(ref id) if id.name == "blockhash") {
return true;
}
}
}
},
_ => ()
}

false
}

#[cfg(test)]
mod weak_randomness_detector_tests {
use crate::detect::{detector::IssueDetector, high::weak_randomness::WeakRandomnessDetector};

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

let mut detector = WeakRandomnessDetector::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(), 9);
// assert the severity is high
assert_eq!(
detector.severity(),
crate::detect::detector::IssueSeverity::High
);
// assert the title is correct
assert_eq!(detector.title(), String::from("Weak Randomness"));
// assert the description is correct
assert_eq!(
detector.description(),
String::from("The use of keccak256 hash functions on predictable values like block.timestamp, block.number, or similar data, including modulo operations on these values, should be avoided for generating randomness, as they are easily predictable and manipulable. The `PREVRANDAO` opcode also should not be used as a source of randomness. Instead, utilize Chainlink VRF for cryptographically secure and provably random values to ensure protocol integrity.")
);
}
}
1 change: 1 addition & 0 deletions reports/adhoc-sol-files-highs-only-report.json
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@
"rtlo",
"unchecked-return",
"dangerous-unary-operator",
"weak-randomness",
"pre-declared-local-variable-usage",
"delete-nested-mapping"
]
Expand Down
96 changes: 93 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": 66,
"total_sloc": 1845
"total_source_units": 67,
"total_sloc": 1904
},
"files_details": {
"files_details": [
Expand Down Expand Up @@ -185,6 +185,10 @@
"file_path": "src/UsingSelfdestruct.sol",
"n_sloc": 6
},
{
"file_path": "src/WeakRandomness.sol",
"n_sloc": 59
},
{
"file_path": "src/WrongOrderOfLayout.sol",
"n_sloc": 13
Expand Down Expand Up @@ -272,7 +276,7 @@
]
},
"issue_count": {
"high": 28,
"high": 29,
"low": 23
},
"high_issues": {
Expand Down Expand Up @@ -1587,6 +1591,67 @@
}
]
},
{
"title": "Weak Randomness",
"description": "The use of keccak256 hash functions on predictable values like block.timestamp, block.number, or similar data, including modulo operations on these values, should be avoided for generating randomness, as they are easily predictable and manipulable. The `PREVRANDAO` opcode also should not be used as a source of randomness. Instead, utilize Chainlink VRF for cryptographically secure and provably random values to ensure protocol integrity.",
"detector_name": "weak-randomness",
"instances": [
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 6,
"src": "188:70",
"src_char": "188:70"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 11,
"src": "386:41",
"src_char": "386:41"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 16,
"src": "597:20",
"src_char": "597:20"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 21,
"src": "793:20",
"src_char": "793:20"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 25,
"src": "915:20",
"src_char": "915:20"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 31,
"src": "1095:5",
"src_char": "1095:5"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 35,
"src": "1217:37",
"src_char": "1217:37"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 41,
"src": "1434:9",
"src_char": "1434:9"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 45,
"src": "1563:16",
"src_char": "1563:16"
}
]
},
{
"title": "Usage of variable before declaration.",
"description": "This is a bad practice that may lead to unintended consequences. Please declare the variable before using it.",
Expand Down Expand Up @@ -2284,6 +2349,24 @@
"src": "1190:7",
"src_char": "1190:7"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 25,
"src": "933:2",
"src_char": "933:2"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 35,
"src": "1252:2",
"src_char": "1252:2"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 41,
"src": "1441:2",
"src_char": "1441:2"
},
{
"contract_path": "src/eth2/DepositContract.sol",
"line_no": 113,
Expand Down Expand Up @@ -2589,6 +2672,12 @@
"src": "32:23",
"src_char": "32:23"
},
{
"contract_path": "src/WeakRandomness.sol",
"line_no": 2,
"src": "32:23",
"src_char": "32:23"
},
{
"contract_path": "src/cloc/AnotherHeavilyCommentedContract.sol",
"line_no": 6,
Expand Down Expand Up @@ -3384,6 +3473,7 @@
"rtlo",
"unchecked-return",
"dangerous-unary-operator",
"weak-randomness",
"pre-declared-local-variable-usage",
"delete-nested-mapping"
]
Expand Down
Loading

0 comments on commit c9c251d

Please sign in to comment.