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

Strip Potentially Sensitive Sections from User WASMs #81

Merged
merged 1 commit into from
Aug 27, 2024
Merged
Changes from all 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
40 changes: 39 additions & 1 deletion check/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@ use brotli2::read::BrotliEncoder;
use cargo_stylus_util::{color::Color, sys};
use eyre::{bail, eyre, Result, WrapErr};
use glob::glob;
use std::process::Command;
use std::{
env::current_dir,
fs,
io::Read,
path::{Path, PathBuf},
process,
};
use std::{ops::Range, process::Command};
use tiny_keccak::{Hasher, Keccak};
use toml::Value;
use wasm_encoder::{Module, RawSection};
use wasmparser::{Parser, Payload};

#[derive(Default, Clone, PartialEq)]
pub enum OptLevel {
Expand Down Expand Up @@ -287,6 +289,10 @@ pub fn compress_wasm(wasm: &PathBuf, project_hash: [u8; 32]) -> Result<(Vec<u8>,

let wasm = add_project_hash_to_wasm_file(&wasm, project_hash)
.wrap_err("failed to add project hash to wasm file as custom section")?;

let wasm =
strip_user_metadata(&wasm).wrap_err("failed to strip user metadata from wasm file")?;

let wasm = wasmer::wat2wasm(&wasm).wrap_err("failed to parse Wasm")?;

let mut compressor = BrotliEncoder::new(&*wasm, BROTLI_COMPRESSION_LEVEL);
Expand Down Expand Up @@ -339,6 +345,38 @@ fn add_custom_section(wasm_file_bytes: &[u8], project_hash: [u8; 32]) -> Vec<u8>
bytes
}

fn strip_user_metadata(wasm_file_bytes: &[u8]) -> Result<Vec<u8>> {
let mut module = Module::new();
// Parse the input WASM and iterate over the sections
let parser = Parser::new(0);
for payload in parser.parse_all(wasm_file_bytes) {
match payload? {
Payload::CustomSection { .. } => {
// Skip custom sections to remove sensitive metadata
greyln!("stripped custom section from user wasm to remove any sensitive data");
}
Payload::UnknownSection { .. } => {
// Skip unknown sections that might not be sensitive
println!("stripped unknown section from user wasm to remove any sensitive data");
}
item => {
// Handle other sections as normal.
if let Some(section) = item.as_section() {
let (id, range): (u8, Range<usize>) = section;
let data_slice = &wasm_file_bytes[range.start..range.end]; // Start at the beginning of the range
let raw_section = RawSection {
id,
data: data_slice,
};
module.section(&raw_section);
}
}
}
}
// Return the stripped WASM binary
Ok(module.finish())
}

#[cfg(test)]
mod test {
use super::*;
Expand Down
Loading