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

Detect write in storage ops in view methods #1771

Merged
merged 17 commits into from
Oct 9, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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
27 changes: 23 additions & 4 deletions framework/meta-lib/src/contract/sc_config/wasm_build.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{ffi::OsStr, fs, process::Command};
use std::{collections::HashMap, ffi::OsStr, fs, process::Command};

use super::ContractVariant;
use crate::{
Expand Down Expand Up @@ -93,6 +93,12 @@ impl ContractVariant {
print_pack_mxsc_file(&output_mxsc_path);
print_contract_size(compiled_bytes.len());
let mut abi = ContractAbiJson::from(&self.abi);
let mut view_endpoints = Vec::new();
for endpoint in &abi.endpoints {
andrei-marinica marked this conversation as resolved.
Show resolved Hide resolved
if let crate::abi_json::EndpointMutabilityAbiJson::Readonly = endpoint.mutability {
view_endpoints.push(&endpoint.name)
}
}
let build_info = core::mem::take(&mut abi.build_info).unwrap();
let ei_check_json = EiCheckJson::new(&self.settings.check_ei, wasm_info.ei_check);
let report = ReportInfoJson::new(&wasm_info, ei_check_json, compiled_bytes.len());
Expand Down Expand Up @@ -130,11 +136,20 @@ impl ContractVariant {
fn extract_wasm_info(&self, build_args: &BuildArgs, output_path: &str) -> WasmInfo {
let output_wasm_path = format!("{output_path}/{}", self.wasm_output_name(build_args));

let abi = ContractAbiJson::from(&self.abi);
let mut view_endpoints: HashMap<&str, usize> = HashMap::new();
for endpoint in &abi.endpoints {
if let crate::abi_json::EndpointMutabilityAbiJson::Readonly = endpoint.mutability {
view_endpoints.insert(&endpoint.name, 0);
}
}

if !build_args.extract_imports {
return WasmInfo::extract_wasm_info(
&output_wasm_path,
build_args.extract_imports,
&self.settings.check_ei,
view_endpoints,
)
.expect("error occured while extracting imports from .wasm ");
}
Expand All @@ -146,9 +161,13 @@ impl ContractVariant {
);
print_extract_imports(&output_imports_json_path);

let wasm_data =
WasmInfo::extract_wasm_info(&output_wasm_path, true, &self.settings.check_ei)
.expect("error occured while extracting imports from .wasm ");
let wasm_data = WasmInfo::extract_wasm_info(
&output_wasm_path,
true,
&self.settings.check_ei,
view_endpoints,
)
.expect("error occured while extracting imports from .wasm ");

write_imports_output(
output_imports_json_path.as_str(),
Expand Down
10 changes: 10 additions & 0 deletions framework/meta-lib/src/tools/report_creator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,13 @@ pub struct ReportCreator {
}

impl ReportCreator {}

impl Default for ReportCreator {
fn default() -> Self {
ReportCreator {
path: String::new(),
has_allocator: false,
has_panic: "none".to_string(),
}
}
}
165 changes: 132 additions & 33 deletions framework/meta-lib/src/tools/wasm_extractor.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,40 @@
use colored::Colorize;
use std::fs;
use std::{
collections::{HashMap, HashSet},
fs,
};
use wasmparser::{
BinaryReaderError, DataSectionReader, FunctionBody, ImportSectionReader, Parser, Payload,
BinaryReaderError, DataSectionReader, ExportSectionReader, FunctionBody, ImportSectionReader,
Operator, Parser, Payload,
};

use crate::ei::EIVersion;

use super::report_creator::{ReportCreator, WITHOUT_MESSAGE, WITH_MESSAGE};

type CallGraph = HashMap<usize, HashSet<usize>>;

const PANIC_WITH_MESSAGE: &[u8; 16] = b"panic occurred: ";
const PANIC_WITHOUT_MESSAGE: &[u8; 14] = b"panic occurred";
const ERROR_FAIL_ALLOCATOR: &[u8; 27] = b"memory allocation forbidden";
const MEMORY_GROW_OPCODE: u8 = 0x40;
const WRITE_OP: [&str; 1] = ["mBufferStorageStore"];
andrei-marinica marked this conversation as resolved.
Show resolved Hide resolved

#[derive(Default)]
pub struct WasmInfo {
pub imports: Vec<String>,
pub ei_check: bool,
pub memory_grow_flag: bool,
pub has_format: bool,
pub report: ReportCreator,
pub call_graph: CallGraph,
}

impl WasmInfo {
pub fn extract_wasm_info(
output_wasm_path: &str,
extract_imports_enabled: bool,
check_ei: &Option<EIVersion>,
view_endpoints: HashMap<&str, usize>,
) -> Result<WasmInfo, BinaryReaderError> {
let wasm_data = fs::read(output_wasm_path)
.expect("error occured while extracting information from .wasm: file not found");
Expand All @@ -35,6 +44,7 @@ impl WasmInfo {
wasm_data,
extract_imports_enabled,
check_ei,
view_endpoints,
)
}
}
Expand All @@ -44,50 +54,136 @@ fn populate_wasm_info(
wasm_data: Vec<u8>,
extract_imports_enabled: bool,
check_ei: &Option<EIVersion>,
mut view_endpoints: HashMap<&str, usize>,
) -> Result<WasmInfo, BinaryReaderError> {
let mut imports = Vec::new();
let mut allocator_trigger = false;
let mut ei_check = false;
let mut memory_grow_flag = false;
let mut has_panic = "none";
let mut wasm_info = WasmInfo::default();
let mut write_functions: HashSet<usize> = HashSet::new();

let parser = Parser::new(0);
for payload in parser.parse_all(&wasm_data) {
match payload? {
Payload::ImportSection(import_section) => {
imports = extract_imports(import_section, extract_imports_enabled);
ei_check = is_ei_valid(imports.clone(), check_ei);
write_functions =
process_imports(import_section, extract_imports_enabled, &mut wasm_info);
wasm_info.ei_check = is_ei_valid(&wasm_info.imports, check_ei);
},
Payload::DataSection(data_section) => {
allocator_trigger = is_fail_allocator_triggered(data_section.clone());
wasm_info.report.has_allocator = is_fail_allocator_triggered(data_section.clone());
if is_panic_with_message_triggered(data_section.clone()) {
has_panic = WITH_MESSAGE;
WITH_MESSAGE.clone_into(&mut wasm_info.report.has_panic);
} else if is_panic_without_message_triggered(data_section) {
has_panic = WITHOUT_MESSAGE;
WITHOUT_MESSAGE.clone_into(&mut wasm_info.report.has_panic);
}
},
Payload::CodeSectionEntry(code_section) => {
memory_grow_flag = is_mem_grow(code_section);
wasm_info.memory_grow_flag = is_mem_grow(&code_section);
create_call_graph(code_section, &mut wasm_info.call_graph);
},
Payload::ExportSection(export_section) => {
parse_export_section(export_section, &mut view_endpoints);
},
_ => (),
}
}

detect_write_operations_in_views(&view_endpoints, &wasm_info.call_graph, &mut write_functions);

let report = ReportCreator {
path,
has_allocator: allocator_trigger,
has_panic: has_panic.to_string(),
has_allocator: wasm_info.report.has_allocator,
has_panic: wasm_info.report.has_panic,
};

Ok(WasmInfo {
imports,
ei_check,
memory_grow_flag,
has_format: true,
imports: wasm_info.imports,
ei_check: wasm_info.ei_check,
memory_grow_flag: wasm_info.memory_grow_flag,
call_graph: wasm_info.call_graph,
report,
})
}

fn detect_write_operations_in_views(
andrei-marinica marked this conversation as resolved.
Show resolved Hide resolved
views_data: &HashMap<&str, usize>,
call_graph: &CallGraph,
write_functions: &mut HashSet<usize>,
) {
let mut visited: HashSet<usize> = HashSet::new();
for index in views_data.values() {
mark_write(*index, call_graph, write_functions, &mut visited);
}

for (name, index) in views_data {
if write_functions.contains(index) {
println!(
"{} {}",
"Write storage operation in VIEW endpoint:"
.to_string()
.red()
.bold(),
name.red().bold()
);
}
}
}

fn parse_export_section(
export_section: ExportSectionReader,
view_endpoints: &mut HashMap<&str, usize>,
) {
for export in export_section {
let export = export.expect("Failed to read export section");
if let wasmparser::ExternalKind::Func = export.kind {
if let Some(endpoint_index) = view_endpoints.get_mut(export.name) {
*endpoint_index = export.index.try_into().unwrap();
}
}
}
}

fn mark_write(
func: usize,
call_graph: &CallGraph,
write_functions: &mut HashSet<usize>,
visited: &mut HashSet<usize>,
) {
// Return early to prevent cycles.
if visited.contains(&func) {
return;
}

visited.insert(func);

if let Some(callees) = call_graph.get(&func) {
for &callee in callees {
if write_functions.contains(&callee) {
write_functions.insert(func);
} else {
mark_write(callee, call_graph, write_functions, visited);
if write_functions.contains(&callee) {
write_functions.insert(func);
}
}
}
}
}

fn create_call_graph(body: FunctionBody, call_graph: &mut CallGraph) {
let mut instructions_reader = body
.get_operators_reader()
.expect("Failed to get operators reader");

let mut call_functions = HashSet::new();
while let Ok(op) = instructions_reader.read() {
if let Operator::Call { function_index } = op {
let function_usize: usize = function_index.try_into().unwrap();
call_functions.insert(function_usize);
}
}

call_graph.insert(call_graph.len(), call_functions);
}

fn is_fail_allocator_triggered(data_section: DataSectionReader) -> bool {
for data_fragment in data_section.into_iter().flatten() {
if data_fragment
Expand Down Expand Up @@ -137,25 +233,28 @@ fn is_panic_without_message_triggered(data_section: DataSectionReader) -> bool {
false
}

pub fn extract_imports(
pub fn process_imports(
import_section: ImportSectionReader,
import_extraction_enabled: bool,
) -> Vec<String> {
if !import_extraction_enabled {
return Vec::new();
}

let mut import_names = Vec::new();
for import in import_section.into_iter().flatten() {
import_names.push(import.name.to_string());
wasm_info: &mut WasmInfo,
) -> HashSet<usize> {
let mut write_functions = HashSet::new();
for (index, import) in import_section.into_iter().flatten().enumerate() {
if import_extraction_enabled {
wasm_info.imports.push(import.name.to_string());
}
wasm_info.call_graph.insert(index, HashSet::new());
if WRITE_OP.contains(&import.name) {
write_functions.insert(index);
}
}

import_names.sort();
wasm_info.imports.sort();

import_names
write_functions
}

fn is_ei_valid(imports: Vec<String>, check_ei: &Option<EIVersion>) -> bool {
fn is_ei_valid(imports: &[String], check_ei: &Option<EIVersion>) -> bool {
if let Some(ei) = check_ei {
let mut num_errors = 0;
for import in imports {
Expand All @@ -172,7 +271,7 @@ fn is_ei_valid(imports: Vec<String>, check_ei: &Option<EIVersion>) -> bool {
false
}

fn is_mem_grow(code_section: FunctionBody) -> bool {
fn is_mem_grow(code_section: &FunctionBody) -> bool {
let mut code = code_section.get_binary_reader();
while code.bytes_remaining() > 0 {
if code.read_u8().unwrap() == MEMORY_GROW_OPCODE {
Expand Down
Loading