|
| 1 | +use std::collections::BTreeMap; |
| 2 | +use std::error::Error; |
| 3 | + |
| 4 | +use crate::ast::{Expression, FunctionCall, FunctionCallKind, NodeID}; |
| 5 | + |
| 6 | +use crate::capture; |
| 7 | +use crate::detect::detector::IssueDetectorNamePool; |
| 8 | +use crate::{ |
| 9 | + context::workspace_context::{ASTNode, WorkspaceContext}, |
| 10 | + detect::detector::{IssueDetector, IssueSeverity}, |
| 11 | +}; |
| 12 | +use eyre::Result; |
| 13 | + |
| 14 | +#[derive(Default)] |
| 15 | +pub struct WeakRandomnessDetector { |
| 16 | + // Keys are: [0] source file name, [1] line number, [2] character location of node. |
| 17 | + // Do not add items manually, use `capture!` to add nodes to this BTreeMap. |
| 18 | + found_instances: BTreeMap<(String, usize, String), NodeID>, |
| 19 | +} |
| 20 | + |
| 21 | +impl IssueDetector for WeakRandomnessDetector { |
| 22 | + fn detect(&mut self, context: &WorkspaceContext) -> Result<bool, Box<dyn Error>> { |
| 23 | + let keccaks: Vec<&FunctionCall> = context.function_calls() |
| 24 | + .into_iter() |
| 25 | + .filter(|x| matches!(*x.expression, Expression::Identifier(ref id) if id.name == "keccak256")) |
| 26 | + .collect(); |
| 27 | + |
| 28 | + for keccak in keccaks { |
| 29 | + // keccak256 must have exactly one argument |
| 30 | + if let Some(arg) = keccak.arguments.first() { |
| 31 | + if let Expression::FunctionCall(ref function_call) = *arg { |
| 32 | + if check_encode(function_call) { |
| 33 | + capture!(self, context, keccak); |
| 34 | + } |
| 35 | + } |
| 36 | + // get variable definition |
| 37 | + else if let Expression::Identifier(ref i) = *arg { |
| 38 | + if let Some(node_id) = i.referenced_declaration { |
| 39 | + let decleration = context.get_parent(node_id); |
| 40 | + |
| 41 | + if let Some(ASTNode::VariableDeclarationStatement(var)) = decleration { |
| 42 | + if let Some(Expression::FunctionCall(function_call)) = |
| 43 | + &var.initial_value |
| 44 | + { |
| 45 | + if check_encode(function_call) { |
| 46 | + capture!(self, context, keccak); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + // check for modulo operations on block.timestamp, block.number and blockhash |
| 56 | + for binary_operation in context |
| 57 | + .binary_operations() |
| 58 | + .into_iter() |
| 59 | + .filter(|b| b.operator == "%") |
| 60 | + { |
| 61 | + // if left operand is a variable, get its definition and perform check |
| 62 | + if let Expression::Identifier(ref i) = *binary_operation.left_expression { |
| 63 | + if let Some(node_id) = i.referenced_declaration { |
| 64 | + let decleration = context.get_parent(node_id); |
| 65 | + |
| 66 | + if let Some(ASTNode::VariableDeclarationStatement(var)) = decleration { |
| 67 | + if let Some(expression) = &var.initial_value { |
| 68 | + if check_operand(expression) { |
| 69 | + capture!(self, context, binary_operation); |
| 70 | + continue; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + // otherwise perform check directly on the expression |
| 77 | + else if check_operand(&binary_operation.left_expression) { |
| 78 | + capture!(self, context, binary_operation); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + // check if contract uses block.prevrandao |
| 83 | + for member_access in context.member_accesses() { |
| 84 | + if member_access.member_name == "prevrandao" |
| 85 | + && matches!(*member_access.expression, Expression::Identifier(ref id) if id.name == "block") |
| 86 | + { |
| 87 | + capture!(self, context, member_access); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + Ok(!self.found_instances.is_empty()) |
| 92 | + } |
| 93 | + |
| 94 | + fn severity(&self) -> IssueSeverity { |
| 95 | + IssueSeverity::High |
| 96 | + } |
| 97 | + |
| 98 | + fn title(&self) -> String { |
| 99 | + String::from("Weak Randomness") |
| 100 | + } |
| 101 | + |
| 102 | + fn description(&self) -> String { |
| 103 | + 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.") |
| 104 | + } |
| 105 | + |
| 106 | + fn instances(&self) -> BTreeMap<(String, usize, String), NodeID> { |
| 107 | + self.found_instances.clone() |
| 108 | + } |
| 109 | + |
| 110 | + fn name(&self) -> String { |
| 111 | + format!("{}", IssueDetectorNamePool::WeakRandomness) |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +// returns whether block.timestamp or block.number is used in encode function |
| 116 | +fn check_encode(function_call: &FunctionCall) -> bool { |
| 117 | + if let Expression::MemberAccess(ref member_access) = *function_call.expression { |
| 118 | + if member_access.member_name == "encodePacked" || member_access.member_name == "encode" { |
| 119 | + for argument in &function_call.arguments { |
| 120 | + if let Expression::MemberAccess(ref member_access) = *argument { |
| 121 | + if ["timestamp", "number"].iter().any(|ma| { |
| 122 | + ma == &member_access.member_name && |
| 123 | + matches!(*member_access.expression, Expression::Identifier(ref id) if id.name == "block") |
| 124 | + }) { |
| 125 | + return true; |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + false |
| 132 | +} |
| 133 | + |
| 134 | +// returns whether operand is dependent on block.timestamp, block.number or blockhash |
| 135 | +fn check_operand(operand: &Expression) -> bool { |
| 136 | + match operand { |
| 137 | + Expression::MemberAccess(member_access) => { |
| 138 | + if ["timestamp", "number"].iter().any(|ma| { |
| 139 | + ma == &member_access.member_name && |
| 140 | + matches!(*member_access.expression, Expression::Identifier(ref id) if id.name == "block") |
| 141 | + }) { |
| 142 | + return true; |
| 143 | + } |
| 144 | + }, |
| 145 | + Expression::FunctionCall(function_call) => { |
| 146 | + if function_call.kind == FunctionCallKind::TypeConversion { |
| 147 | + // type conversion must have exactly one argument |
| 148 | + if let Some(Expression::FunctionCall(ref inner_function_call)) = function_call.arguments.first() { |
| 149 | + if matches!(*inner_function_call.expression, Expression::Identifier(ref id) if id.name == "blockhash") { |
| 150 | + return true; |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + }, |
| 155 | + _ => () |
| 156 | + } |
| 157 | + |
| 158 | + false |
| 159 | +} |
| 160 | + |
| 161 | +#[cfg(test)] |
| 162 | +mod weak_randomness_detector_tests { |
| 163 | + use crate::detect::{detector::IssueDetector, high::weak_randomness::WeakRandomnessDetector}; |
| 164 | + |
| 165 | + #[test] |
| 166 | + fn test_weak_randomness_detector() { |
| 167 | + let context = crate::detect::test_utils::load_solidity_source_unit( |
| 168 | + "../tests/contract-playground/src/WeakRandomness.sol", |
| 169 | + ); |
| 170 | + |
| 171 | + let mut detector = WeakRandomnessDetector::default(); |
| 172 | + let found = detector.detect(&context).unwrap(); |
| 173 | + // assert that the detector found an issue |
| 174 | + assert!(found); |
| 175 | + // assert that the detector found the correct number of instances |
| 176 | + assert_eq!(detector.instances().len(), 9); |
| 177 | + // assert the severity is high |
| 178 | + assert_eq!( |
| 179 | + detector.severity(), |
| 180 | + crate::detect::detector::IssueSeverity::High |
| 181 | + ); |
| 182 | + // assert the title is correct |
| 183 | + assert_eq!(detector.title(), String::from("Weak Randomness")); |
| 184 | + // assert the description is correct |
| 185 | + assert_eq!( |
| 186 | + detector.description(), |
| 187 | + 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.") |
| 188 | + ); |
| 189 | + } |
| 190 | +} |
0 commit comments