diff --git a/.github/workflows/reproducible.yml b/.github/workflows/reproducible.yml new file mode 100644 index 0000000..44f816c --- /dev/null +++ b/.github/workflows/reproducible.yml @@ -0,0 +1,40 @@ +--- +name: Check that binaries are reproducible +on: + push: + pull_request: + types: [opened, synchronize, reopened] + +jobs: + check_hashes: + strategy: + matrix: + os: [ubuntu-18.04, macos-10.15] + fail-fast: false + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + target: thumbv7em-none-eabi + - uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: Install Python dependencies + run: python -m pip install --upgrade pip setuptools wheel + - name: Set up OpenSK + run: ./setup.sh + + - name: Use sample cryptographic material + run: rm -R crypto_data/ && cp -r reproducible/sample_crypto_data crypto_data + - name: Computing cryptographic hashes + run: ./reproduce_hashes.sh + + - name: Upload reproduced binaries + uses: actions/upload-artifact@v1 + with: + name: reproduced-${{ matrix.os }} + path: reproducible/reproduced.tar + + - name: Comparing cryptographic hashes + run: git diff --no-index reproducible/reference_binaries_${{ matrix.os }}.sha256sum reproducible/binaries.sha256sum diff --git a/deploy.py b/deploy.py index 57b7b86..38be497 100755 --- a/deploy.py +++ b/deploy.py @@ -60,6 +60,10 @@ OpenSKBoard = collections.namedtuple( "app_ldscript", # Flash address at which the app should be written "app_address", + # Flash address of the storage + "storage_address", + # Size of the storage + "storage_size", # Target name for flashing the board using pyOCD "pyocd_target", # The cfg file in OpenOCD board folder @@ -89,6 +93,8 @@ SUPPORTED_BOARDS = { padding_address=0x30000, app_ldscript="nrf52840_layout.ld", app_address=0x40000, + storage_address=0xC0000, + storage_size=0x40000, pyocd_target="nrf52840", openocd_board="nordic_nrf52840_dongle.cfg", openocd_options=[], @@ -106,6 +112,8 @@ SUPPORTED_BOARDS = { padding_address=0x30000, app_ldscript="nrf52840_layout.ld", app_address=0x40000, + storage_address=0xC0000, + storage_size=0x40000, pyocd_target="nrf52840", openocd_board="nordic_nrf52840_dongle.cfg", openocd_options=[], @@ -123,6 +131,8 @@ SUPPORTED_BOARDS = { padding_address=0x30000, app_ldscript="nrf52840_layout.ld", app_address=0x40000, + storage_address=0xC0000, + storage_size=0x40000, pyocd_target="nrf52840", openocd_board="nordic_nrf52840_dongle.cfg", openocd_options=[], @@ -140,6 +150,8 @@ SUPPORTED_BOARDS = { padding_address=0x30000, app_ldscript="nrf52840_layout.ld", app_address=0x40000, + storage_address=0xC0000, + storage_size=0x40000, pyocd_target="nrf52840", openocd_board="nordic_nrf52840_dongle.cfg", openocd_options=[], @@ -392,19 +404,18 @@ class OpenSKInstaller: assert self.args.application info("Generating Tock TAB file for application/example {}".format( self.args.application)) - package_parameter = "-n" elf2tab_ver = self.checked_command_output(["elf2tab", "--version"]).split( - " ", maxsplit=1)[1] - # Starting from v0.5.0-dev the parameter changed. - # Current pyblished crate is 0.4.0 but we don't want developers - # running the HEAD from github to be stuck - if "0.5.0-dev" in elf2tab_ver: - package_parameter = "--package-name" + "\n", maxsplit=1)[0] + if elf2tab_ver != "elf2tab 0.5.0": + error( + ("Detected unsupported elf2tab version {!a}. The following " + "commands may fail. Please use 0.5.0 instead.").format(elf2tab_ver)) os.makedirs(self.tab_folder, exist_ok=True) tab_filename = os.path.join(self.tab_folder, "{}.tab".format(self.args.application)) elf2tab_args = [ - "elf2tab", package_parameter, self.args.application, "-o", tab_filename + "elf2tab", "--deterministic", "--package-name", self.args.application, + "-o", tab_filename ] if self.args.verbose_build: elf2tab_args.append("--verbose") @@ -494,6 +505,30 @@ class OpenSKInstaller: info(("A non-critical error occurred while erasing " "apps: {}".format(str(e)))) + def clear_storage(self): + if self.args.programmer == "none": + return 0 + info("Erasing the persistent storage") + board_props = SUPPORTED_BOARDS[self.args.board] + # Use tockloader if possible + if self.args.programmer in ("jlink", "openocd"): + storage = bytes([0xFF] * board_props.storage_size) + tock = loader.TockLoader(self.tockloader_default_args) + tock.open() + try: + tock.flash_binary(storage, board_props.storage_address) + except TockLoaderException as e: + fatal("Couldn't erase the persistent storage: {}".format(str(e))) + return 0 + if self.args.programmer == "pyocd": + self.checked_command([ + "pyocd", "erase", "--target={}".format(board_props.pyocd_target), + "--sector", "{}+{}".format(board_props.storage_address, + board_props.storage_size) + ]) + return 0 + fatal("Programmer {} is not supported.".format(self.args.programmer)) + # pylint: disable=protected-access def verify_flashed_app(self, expected_app): if self.args.programmer not in ("jlink", "openocd"): @@ -595,7 +630,8 @@ class OpenSKInstaller: self.check_prerequisites() self.update_rustc_if_needed() - if not self.args.tockos and not self.args.application: + if not (self.args.tockos or self.args.application or + self.args.clear_storage): info("Nothing to do.") return 0 @@ -611,6 +647,10 @@ class OpenSKInstaller: else: self.build_example() + # Erase persistent storage + if self.args.clear_storage: + self.clear_storage() + # Flashing board_props = SUPPORTED_BOARDS[self.args.board] if self.args.programmer in ("jlink", "openocd"): @@ -718,6 +758,14 @@ if __name__ == "__main__": help=("When installing an application, previously installed " "applications won't be erased from the board."), ) + main_parser.add_argument( + "--clear-storage", + action="store_true", + default=False, + dest="clear_storage", + help=("Erases the persistent storage when installing an application. " + "All stored data will be permanently lost."), + ) main_parser.add_argument( "--programmer", metavar="METHOD", diff --git a/layout.ld b/layout.ld index 5bc9d0c..fde1c40 100644 --- a/layout.ld +++ b/layout.ld @@ -71,18 +71,6 @@ SECTIONS { . = ALIGN(32); } > FLASH =0xFF - /* App state section. Used for persistent app data. - * We put this first because this is what libtock-c does. They provide the - * following explanation: if the app code changes but the persistent data - * doesn't, the app_state can be preserved. - */ - .wfr.app_state : - { - . = ALIGN(4K); - KEEP (*(.app_state)) - . = ALIGN(4K); - } > FLASH =0xFFFFFFFF - /* Text section, Code! */ .text : { diff --git a/libraries/cbor/src/writer.rs b/libraries/cbor/src/writer.rs index 1273160..0764851 100644 --- a/libraries/cbor/src/writer.rs +++ b/libraries/cbor/src/writer.rs @@ -36,7 +36,7 @@ impl<'a> Writer<'a> { return false; } match value { - Value::KeyValue(KeyType::Unsigned(unsigned)) => self.start_item(0, unsigned as u64), + Value::KeyValue(KeyType::Unsigned(unsigned)) => self.start_item(0, unsigned), Value::KeyValue(KeyType::Negative(negative)) => { self.start_item(1, -(negative + 1) as u64) } diff --git a/nrf52840_layout.ld b/nrf52840_layout.ld index 218b6bb..8292738 100644 --- a/nrf52840_layout.ld +++ b/nrf52840_layout.ld @@ -3,8 +3,10 @@ */ MEMORY { - /* The application region is 64 bytes (0x40) */ - FLASH (rx) : ORIGIN = 0x00040040, LENGTH = 0x000BFFC0 + /* The application region is 64 bytes (0x40) and we reserve 0x40000 at the end + * of the flash for the persistent storage. + */ + FLASH (rx) : ORIGIN = 0x00040040, LENGTH = 0x0007FFC0 SRAM (rwx) : ORIGIN = 0x20020000, LENGTH = 128K } diff --git a/patches/tock/01-persistent-storage.patch b/patches/tock/01-persistent-storage.patch index 57880c6..2584a2a 100644 --- a/patches/tock/01-persistent-storage.patch +++ b/patches/tock/01-persistent-storage.patch @@ -1,5 +1,33 @@ +diff --git a/boards/nordic/nrf52840dk/src/main.rs b/boards/nordic/nrf52840dk/src/main.rs +index 44a6c1cc..2ebc2868 100644 +--- a/boards/nordic/nrf52840dk/src/main.rs ++++ b/boards/nordic/nrf52840dk/src/main.rs +@@ -117,6 +117,11 @@ static mut APP_MEMORY: [u8; 0x3C000] = [0; 0x3C000]; + static mut PROCESSES: [Option<&'static dyn kernel::procs::ProcessType>; NUM_PROCS] = + [None, None, None, None, None, None, None, None]; + ++static mut STORAGE_LOCATIONS: [kernel::StorageLocation; 1] = [kernel::StorageLocation { ++ address: 0xC0000, ++ size: 0x40000, ++}]; ++ + static mut CHIP: Option<&'static nrf52840::chip::Chip> = None; + + /// Dummy buffer that causes the linker to reserve enough space for the stack. +@@ -146,7 +151,10 @@ pub unsafe fn reset_handler() { + UartChannel::Pins(UartPins::new(UART_RTS, UART_TXD, UART_CTS, UART_RXD)) + }; + +- let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&PROCESSES)); ++ let board_kernel = static_init!( ++ kernel::Kernel, ++ kernel::Kernel::new_with_storage(&PROCESSES, &STORAGE_LOCATIONS) ++ ); + let gpio = components::gpio::GpioComponent::new(board_kernel).finalize( + components::gpio_component_helper!( + &nrf52840::gpio::PORT[Pin::P1_01], diff --git a/boards/nordic/nrf52dk_base/src/lib.rs b/boards/nordic/nrf52dk_base/src/lib.rs -index fe493727..105f7120 100644 +index 5dd4328e..a117d35f 100644 --- a/boards/nordic/nrf52dk_base/src/lib.rs +++ b/boards/nordic/nrf52dk_base/src/lib.rs @@ -104,6 +104,7 @@ pub struct Platform { @@ -10,7 +38,7 @@ index fe493727..105f7120 100644 } impl kernel::Platform for Platform { -@@ -128,6 +129,7 @@ impl kernel::Platform for Platform { +@@ -128,10 +129,30 @@ impl kernel::Platform for Platform { capsules::nonvolatile_storage_driver::DRIVER_NUM => { f(self.nonvolatile_storage.map_or(None, |nv| Some(nv))) } @@ -18,7 +46,30 @@ index fe493727..105f7120 100644 kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)), _ => f(None), } -@@ -405,6 +407,14 @@ pub unsafe fn setup_board( + } ++ ++ fn filter_syscall( ++ &self, ++ process: &dyn kernel::procs::ProcessType, ++ syscall: &kernel::syscall::Syscall, ++ ) -> Result<(), kernel::ReturnCode> { ++ use kernel::syscall::Syscall; ++ match *syscall { ++ Syscall::COMMAND { ++ driver_number: nrf52::nvmc::DRIVER_NUM, ++ subdriver_number: cmd, ++ arg0: ptr, ++ arg1: len, ++ } if (cmd == 2 || cmd == 3) && !process.fits_in_storage_location(ptr, len) => { ++ Err(kernel::ReturnCode::EINVAL) ++ } ++ _ => Ok(()), ++ } ++ } + } + + /// Generic function for starting an nrf52dk board. +@@ -405,6 +426,14 @@ pub unsafe fn setup_board( ); nrf52::acomp::ACOMP.set_client(analog_comparator); @@ -26,14 +77,14 @@ index fe493727..105f7120 100644 + nrf52::nvmc::SyscallDriver, + nrf52::nvmc::SyscallDriver::new( + &nrf52::nvmc::NVMC, -+ board_kernel.create_grant(&memory_allocation_capability) ++ board_kernel.create_grant(&memory_allocation_capability), + ) + ); + // Start all of the clocks. Low power operation will require a better // approach than this. nrf52::clock::CLOCK.low_stop(); -@@ -439,6 +449,7 @@ pub unsafe fn setup_board( +@@ -431,6 +460,7 @@ pub unsafe fn setup_board( analog_comparator: analog_comparator, nonvolatile_storage: nonvolatile_storage, ipc: kernel::ipc::IPC::new(board_kernel, &memory_allocation_capability), @@ -42,7 +93,7 @@ index fe493727..105f7120 100644 platform.pconsole.start(); diff --git a/chips/nrf52/src/nvmc.rs b/chips/nrf52/src/nvmc.rs -index 5abd2d84..5a726fdb 100644 +index 60fc2da8..ca41b899 100644 --- a/chips/nrf52/src/nvmc.rs +++ b/chips/nrf52/src/nvmc.rs @@ -3,6 +3,7 @@ @@ -97,7 +148,7 @@ index 5abd2d84..5a726fdb 100644 while !self.is_ready() {} } -@@ -314,7 +326,7 @@ impl Nvmc { +@@ -322,7 +334,7 @@ impl Nvmc { // Put the NVMC in write mode. regs.config.write(Configuration::WEN::Wen); @@ -106,7 +157,7 @@ index 5abd2d84..5a726fdb 100644 let word: u32 = (data[i + 0] as u32) << 0 | (data[i + 1] as u32) << 8 | (data[i + 2] as u32) << 16 -@@ -374,3 +386,178 @@ impl hil::flash::Flash for Nvmc { +@@ -390,3 +402,180 @@ impl hil::flash::Flash for Nvmc { self.erase_page(page_number) } } @@ -138,12 +189,12 @@ index 5abd2d84..5a726fdb 100644 +/// - COMMAND(1, 2): Get the maximum number of word writes between page erasures (always 2). +/// - COMMAND(1, 3): Get the maximum number page erasures in the lifetime of the flash (always +/// 10000). -+/// - COMMAND(2, ptr): Write the allow slice to the flash region starting at `ptr`. ++/// - COMMAND(2, ptr, len): Write the allow slice to the flash region starting at `ptr`. +/// - `ptr` must be word-aligned. +/// - The allow slice length must be word aligned. +/// - The region starting at `ptr` of the same length as the allow slice must be in a writeable +/// flash region. -+/// - COMMAND(3, ptr): Erase a page. ++/// - COMMAND(3, ptr, len): Erase a page. +/// - `ptr` must be page-aligned. +/// - The page starting at `ptr` must be in a writeable flash region. +/// - ALLOW(0): The allow slice for COMMAND(2). @@ -189,11 +240,8 @@ index 5abd2d84..5a726fdb 100644 + /// Fails with `EINVAL` if any of the following conditions does not hold: + /// - `ptr` must be word-aligned. + /// - `slice.len()` must be word-aligned. -+ /// - The slice starting at `ptr` of length `slice.len()` must fit in a writeable flash region. -+ fn write_slice(&self, appid: AppId, ptr: usize, slice: &[u8]) -> ReturnCode { -+ if !appid.in_writeable_flash_region(ptr, slice.len()) { -+ return ReturnCode::EINVAL; -+ } ++ /// - The slice starting at `ptr` of length `slice.len()` must fit in the storage. ++ fn write_slice(&self, ptr: usize, slice: &[u8]) -> ReturnCode { + if ptr & WORD_MASK != 0 || slice.len() & WORD_MASK != 0 { + return ReturnCode::EINVAL; + } @@ -217,11 +265,8 @@ index 5abd2d84..5a726fdb 100644 + /// + /// Fails with `EINVAL` if any of the following conditions does not hold: + /// - `ptr` must be page-aligned. -+ /// - The slice starting at `ptr` of length `PAGE_SIZE` must fit in a writeable flash region. -+ fn erase_page(&self, appid: AppId, ptr: usize) -> ReturnCode { -+ if !appid.in_writeable_flash_region(ptr, PAGE_SIZE) { -+ return ReturnCode::EINVAL; -+ } ++ /// - The slice starting at `ptr` of length `PAGE_SIZE` must fit in the storage. ++ fn erase_page(&self, ptr: usize) -> ReturnCode { + if ptr & PAGE_MASK != 0 { + return ReturnCode::EINVAL; + } @@ -236,32 +281,40 @@ index 5abd2d84..5a726fdb 100644 + ReturnCode::ENOSUPPORT + } + -+ fn command(&self, cmd: usize, arg: usize, _: usize, appid: AppId) -> ReturnCode { -+ match (cmd, arg) { -+ (0, _) => ReturnCode::SUCCESS, ++ fn command(&self, cmd: usize, arg0: usize, arg1: usize, appid: AppId) -> ReturnCode { ++ match (cmd, arg0, arg1) { ++ (0, _, _) => ReturnCode::SUCCESS, + -+ (1, 0) => ReturnCode::SuccessWithValue { value: WORD_SIZE }, -+ (1, 1) => ReturnCode::SuccessWithValue { value: PAGE_SIZE }, -+ (1, 2) => ReturnCode::SuccessWithValue { ++ (1, 0, _) => ReturnCode::SuccessWithValue { value: WORD_SIZE }, ++ (1, 1, _) => ReturnCode::SuccessWithValue { value: PAGE_SIZE }, ++ (1, 2, _) => ReturnCode::SuccessWithValue { + value: MAX_WORD_WRITES, + }, -+ (1, 3) => ReturnCode::SuccessWithValue { ++ (1, 3, _) => ReturnCode::SuccessWithValue { + value: MAX_PAGE_ERASES, + }, -+ (1, _) => ReturnCode::EINVAL, ++ (1, _, _) => ReturnCode::EINVAL, + -+ (2, ptr) => self ++ (2, ptr, len) => self + .apps + .enter(appid, |app, _| { + let slice = match app.slice.take() { + None => return ReturnCode::EINVAL, + Some(slice) => slice, + }; -+ self.write_slice(appid, ptr, slice.as_ref()) ++ if len != slice.len() { ++ return ReturnCode::EINVAL; ++ } ++ self.write_slice(ptr, slice.as_ref()) + }) + .unwrap_or_else(|err| err.into()), + -+ (3, ptr) => self.erase_page(appid, ptr), ++ (3, ptr, len) => { ++ if len != PAGE_SIZE { ++ return ReturnCode::EINVAL; ++ } ++ self.erase_page(ptr) ++ } + + _ => ReturnCode::ENOSUPPORT, + } @@ -285,39 +338,187 @@ index 5abd2d84..5a726fdb 100644 + } + } +} -diff --git a/kernel/src/callback.rs b/kernel/src/callback.rs -index c812e0bf..bd1613b3 100644 ---- a/kernel/src/callback.rs -+++ b/kernel/src/callback.rs -@@ -130,6 +130,31 @@ impl AppId { - (start, end) - }) - } +diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs +index ebe8052a..a6dcd278 100644 +--- a/kernel/src/lib.rs ++++ b/kernel/src/lib.rs +@@ -47,7 +47,7 @@ pub use crate::platform::systick::SysTick; + pub use crate::platform::{mpu, Chip, Platform}; + pub use crate::platform::{ClockInterface, NoClockControl, NO_CLOCK_CONTROL}; + pub use crate::returncode::ReturnCode; +-pub use crate::sched::Kernel; ++pub use crate::sched::{Kernel, StorageLocation}; + + // Export only select items from the process module. To remove the name conflict + // this cannot be called `process`, so we use a shortened version. These +diff --git a/kernel/src/memop.rs b/kernel/src/memop.rs +index 7537d2b4..61870ccd 100644 +--- a/kernel/src/memop.rs ++++ b/kernel/src/memop.rs +@@ -108,6 +108,25 @@ crate fn memop(process: &dyn ProcessType, op_type: usize, r1: usize) -> ReturnCo + ReturnCode::SUCCESS + } + ++ // Op Type 12: Number of storage locations. ++ 12 => ReturnCode::SuccessWithValue { value: process.number_storage_locations() }, + -+ pub fn in_writeable_flash_region(&self, ptr: usize, len: usize) -> bool { -+ self.kernel.process_map_or(false, *self, |process| { -+ let ptr = match ptr.checked_sub(process.flash_start() as usize) { -+ None => return false, -+ Some(ptr) => ptr, -+ }; -+ (0..process.number_writeable_flash_regions()).any(|i| { -+ let (region_ptr, region_len) = process.get_writeable_flash_region(i); -+ let region_ptr = region_ptr as usize; -+ let region_len = region_len as usize; -+ // We want to check the 2 following inequalities: -+ // (1) `region_ptr <= ptr` -+ // (2) `ptr + len <= region_ptr + region_len` -+ // However, the second one may overflow written as is. We introduce a third -+ // inequality to solve this issue: -+ // (3) `len <= region_len` -+ // Using this third inequality, we can rewrite the second one as: -+ // (4) `ptr - region_ptr <= region_len - len` -+ // This fourth inequality is equivalent to the second one but doesn't overflow when -+ // the first and third inequalities hold. -+ region_ptr <= ptr && len <= region_len && ptr - region_ptr <= region_len - len -+ }) ++ // Op Type 13: The start address of the storage location indexed by r1. ++ 13 => { ++ match process.get_storage_location(r1) { ++ None => ReturnCode::FAIL, ++ Some(x) => ReturnCode::SuccessWithValue { value: x.address } ++ } ++ } ++ ++ // Op Type 14: The size of the storage location indexed by r1. ++ 14 => { ++ match process.get_storage_location(r1) { ++ None => ReturnCode::FAIL, ++ Some(x) => ReturnCode::SuccessWithValue { value: x.size } ++ } ++ } ++ + _ => ReturnCode::ENOSUPPORT, + } + } +diff --git a/kernel/src/process.rs b/kernel/src/process.rs +index eb00f274..41243c8e 100644 +--- a/kernel/src/process.rs ++++ b/kernel/src/process.rs +@@ -281,6 +281,15 @@ pub trait ProcessType { + /// writeable flash region. + fn get_writeable_flash_region(&self, region_index: usize) -> (u32, u32); + ++ /// How many storage locations are defined for this process. ++ fn number_storage_locations(&self) -> usize; ++ ++ /// Get the i-th storage location. ++ fn get_storage_location(&self, index: usize) -> Option<&crate::StorageLocation>; ++ ++ /// Whether a slice fits in a storage location. ++ fn fits_in_storage_location(&self, ptr: usize, len: usize) -> bool; ++ + /// Debug function to update the kernel on where the stack starts for this + /// process. Processes are not required to call this through the memop + /// system call, but it aids in debugging the process. +@@ -999,6 +1008,32 @@ impl ProcessType for Process<'a, C> { + self.header.get_writeable_flash_region(region_index) + } + ++ fn number_storage_locations(&self) -> usize { ++ self.kernel.storage_locations().len() ++ } ++ ++ fn get_storage_location(&self, index: usize) -> Option<&crate::StorageLocation> { ++ self.kernel.storage_locations().get(index) ++ } ++ ++ fn fits_in_storage_location(&self, ptr: usize, len: usize) -> bool { ++ self.kernel.storage_locations().iter().any(|storage_location| { ++ let storage_ptr = storage_location.address; ++ let storage_len = storage_location.size; ++ // We want to check the 2 following inequalities: ++ // (1) `storage_ptr <= ptr` ++ // (2) `ptr + len <= storage_ptr + storage_len` ++ // However, the second one may overflow written as is. We introduce a third ++ // inequality to solve this issue: ++ // (3) `len <= storage_len` ++ // Using this third inequality, we can rewrite the second one as: ++ // (4) `ptr - storage_ptr <= storage_len - len` ++ // This fourth inequality is equivalent to the second one but doesn't overflow when ++ // the first and third inequalities hold. ++ storage_ptr <= ptr && len <= storage_len && ptr - storage_ptr <= storage_len - len + }) + } - } ++ + fn update_stack_start_pointer(&self, stack_pointer: *const u8) { + if stack_pointer >= self.mem_start() && stack_pointer < self.mem_end() { + self.debug.map(|debug| { +@@ -1604,6 +1639,33 @@ impl Process<'a, C> { + return Ok((None, 0)); + } - /// Type to uniquely identify a callback subscription across all drivers. ++ // Allocate MPU region for the storage locations. The storage locations are currently ++ // readable by all processes due to lack of stable app id. ++ for storage_location in kernel.storage_locations() { ++ if chip ++ .mpu() ++ .allocate_region( ++ storage_location.address as *const u8, ++ storage_location.size, ++ storage_location.size, ++ mpu::Permissions::ReadOnly, ++ &mut mpu_config, ++ ) ++ .is_some() ++ { ++ continue; ++ } ++ if config::CONFIG.debug_load_processes { ++ debug!( ++ "[!] flash=[{:#010X}:{:#010X}] process={:?} - couldn't allocate flash region", ++ storage_location.address, ++ storage_location.address + storage_location.size, ++ process_name ++ ); ++ } ++ return Ok((None, 0)); ++ } ++ + // Determine how much space we need in the application's + // memory space just for kernel and grant state. We need to make + // sure we allocate enough memory just for that. +diff --git a/kernel/src/sched.rs b/kernel/src/sched.rs +index fbd68319..43cce76f 100644 +--- a/kernel/src/sched.rs ++++ b/kernel/src/sched.rs +@@ -24,6 +24,12 @@ const KERNEL_TICK_DURATION_US: u32 = 10000; + /// Skip re-scheduling a process if its quanta is nearly exhausted + const MIN_QUANTA_THRESHOLD_US: u32 = 500; + ++/// Represents a storage location in flash. ++pub struct StorageLocation { ++ pub address: usize, ++ pub size: usize, ++} ++ + /// Main object for the kernel. Each board will need to create one. + pub struct Kernel { + /// How many "to-do" items exist at any given time. These include +@@ -33,6 +39,9 @@ pub struct Kernel { + /// This holds a pointer to the static array of Process pointers. + processes: &'static [Option<&'static dyn process::ProcessType>], + ++ /// List of storage locations. ++ storage_locations: &'static [StorageLocation], ++ + /// A counter which keeps track of how many process identifiers have been + /// created. This is used to create new unique identifiers for processes. + process_identifier_max: Cell, +@@ -51,9 +60,17 @@ pub struct Kernel { + + impl Kernel { + pub fn new(processes: &'static [Option<&'static dyn process::ProcessType>]) -> Kernel { ++ Kernel::new_with_storage(processes, &[]) ++ } ++ ++ pub fn new_with_storage( ++ processes: &'static [Option<&'static dyn process::ProcessType>], ++ storage_locations: &'static [StorageLocation], ++ ) -> Kernel { + Kernel { + work: Cell::new(0), + processes: processes, ++ storage_locations: storage_locations, + process_identifier_max: Cell::new(0), + grant_counter: Cell::new(0), + grants_finalized: Cell::new(false), +@@ -599,4 +616,8 @@ impl Kernel { + } + systick.reset(); + } ++ ++ pub fn storage_locations(&self) -> &'static [StorageLocation] { ++ self.storage_locations ++ } + } diff --git a/patches/tock/02-usb.patch b/patches/tock/02-usb.patch index 55f807b..d062c28 100644 --- a/patches/tock/02-usb.patch +++ b/patches/tock/02-usb.patch @@ -14,7 +14,7 @@ diff --git a/boards/nordic/nrf52840dk/src/main.rs b/boards/nordic/nrf52840dk/src index 127c4f2f..a5847805 100644 --- a/boards/nordic/nrf52840dk/src/main.rs +++ b/boards/nordic/nrf52840dk/src/main.rs -@@ -236,6 +236,7 @@ pub unsafe fn reset_handler() { +@@ -244,6 +244,7 @@ pub unsafe fn reset_handler() { FAULT_RESPONSE, nrf52840::uicr::Regulator0Output::DEFAULT, false, @@ -62,7 +62,7 @@ index 105f7120..535e5cd8 100644 kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)), _ => f(None), } -@@ -157,6 +167,7 @@ pub unsafe fn setup_board( +@@ -176,6 +186,7 @@ pub unsafe fn setup_board( app_fault_response: kernel::procs::FaultResponse, reg_vout: Regulator0Output, nfc_as_gpios: bool, @@ -70,7 +70,7 @@ index 105f7120..535e5cd8 100644 chip: &'static nrf52::chip::NRF52, ) { // Make non-volatile memory writable and activate the reset button -@@ -415,6 +426,44 @@ pub unsafe fn setup_board( +@@ -434,6 +445,44 @@ pub unsafe fn setup_board( ) ); @@ -115,7 +115,7 @@ index 105f7120..535e5cd8 100644 // Start all of the clocks. Low power operation will require a better // approach than this. nrf52::clock::CLOCK.low_stop(); -@@ -447,6 +496,7 @@ pub unsafe fn setup_board( +@@ -458,6 +507,7 @@ pub unsafe fn setup_board( temp: temp, alarm: alarm, analog_comparator: analog_comparator, diff --git a/reproduce_board.sh b/reproduce_board.sh new file mode 100755 index 0000000..19730e8 --- /dev/null +++ b/reproduce_board.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -ex + +echo "Board: $BOARD" +./deploy.py --verbose-build --board=$BOARD --no-app --programmer=none +./third_party/tock/tools/sha256sum/target/debug/sha256sum third_party/tock/target/thumbv7em-none-eabi/release/$BOARD.bin >> reproducible/binaries.sha256sum +tar -rvf reproducible/reproduced.tar third_party/tock/target/thumbv7em-none-eabi/release/$BOARD.bin + +./deploy.py --verbose-build --board=$BOARD --opensk --programmer=none +./third_party/tock/tools/sha256sum/target/debug/sha256sum target/${BOARD}_merged.hex >> reproducible/binaries.sha256sum +tar -rvf reproducible/reproduced.tar target/${BOARD}_merged.hex diff --git a/reproduce_hashes.sh b/reproduce_hashes.sh new file mode 100755 index 0000000..9480472 --- /dev/null +++ b/reproduce_hashes.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Copyright 2019 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -ex + +rm -f reproducible/binaries.sha256sum + +echo "Creating reproducible/reproduced.tar" +touch empty_file +tar -cvf reproducible/reproduced.tar empty_file +rm empty_file + +echo "Building sha256sum tool..." +cargo build --manifest-path third_party/tock/tools/sha256sum/Cargo.toml + +echo "Computing SHA-256 sums of the boards..." +for board in nrf52840dk nrf52840_dongle nrf52840_dongle_dfu nrf52840_mdk_dfu +do + BOARD=$board ./reproduce_board.sh +done + +echo "Computing SHA-256 sum of the TAB file..." +./third_party/tock/tools/sha256sum/target/debug/sha256sum target/tab/ctap2.tab >> reproducible/binaries.sha256sum +tar -rvf reproducible/reproduced.tar target/tab/ctap2.tab diff --git a/reproducible/reference_binaries_macos-10.15.sha256sum b/reproducible/reference_binaries_macos-10.15.sha256sum new file mode 100644 index 0000000..98b20af --- /dev/null +++ b/reproducible/reference_binaries_macos-10.15.sha256sum @@ -0,0 +1,9 @@ +1003863864e06553e730eec6df4bf8d30c99f697ef9380efdc35eba679b4db78 third_party/tock/target/thumbv7em-none-eabi/release/nrf52840dk.bin +84d97929d7592d89c7f321ffccafa4148263607e28918e53d9286be8ca55c209 target/nrf52840dk_merged.hex +88f00a5e1dae6ab3f7571c254ac75f5f3e29ebea7f3ca46c16cfdc3708e804fc third_party/tock/target/thumbv7em-none-eabi/release/nrf52840_dongle.bin +02009688b6ef8583f78f9b94ba8af65dfa3749b20516972cdb0d8ea7ac409268 target/nrf52840_dongle_merged.hex +1bc69b48a2c48da55db8b322902e1fe3f2e095c0dd8517db28837d86e0addc85 third_party/tock/target/thumbv7em-none-eabi/release/nrf52840_dongle_dfu.bin +a24e7459b93eea1fc7557ecd9e4271a2ed729425990d6198be6791f364b1384b target/nrf52840_dongle_dfu_merged.hex +f38ee31d3a09e7e11848e78b5318f95517b6dcd076afcb37e6e3d3e5e9995cc7 third_party/tock/target/thumbv7em-none-eabi/release/nrf52840_mdk_dfu.bin +5315b77b997952de10e239289e54b44c24105646f2411074332bb46f4b686ae6 target/nrf52840_mdk_dfu_merged.hex +9012744b93f8bac122fa18916cf8c22d1b8f729a284366802ed222bbc985e3f0 target/tab/ctap2.tab diff --git a/reproducible/reference_binaries_ubuntu-18.04.sha256sum b/reproducible/reference_binaries_ubuntu-18.04.sha256sum new file mode 100644 index 0000000..3171ce7 --- /dev/null +++ b/reproducible/reference_binaries_ubuntu-18.04.sha256sum @@ -0,0 +1,9 @@ +c182bb4902fff51b2f56810fc2a27df3646cd66ba21359162354d53445623ab8 third_party/tock/target/thumbv7em-none-eabi/release/nrf52840dk.bin +805ca30b898b41a091cc136ab9b78b4e566e10c5469902d18c326c132ed4193e target/nrf52840dk_merged.hex +0a9929ba8fa57e8a502a49fc7c53177397202e1b11f4c7c3cb6ed68b2b99dd46 third_party/tock/target/thumbv7em-none-eabi/release/nrf52840_dongle.bin +960dce1eb78f34a3c4cfdb543314da8ce211dced41f34da053669c8773926e1d target/nrf52840_dongle_merged.hex +cca9086c9149c607589b23ffa599a5e4c26db7c20bd3700b79528bd3a5df991d third_party/tock/target/thumbv7em-none-eabi/release/nrf52840_dongle_dfu.bin +1755746cb3a28162a0bbd0b994332fa9ffaedca684803dfd9ef584040cea73ca target/nrf52840_dongle_dfu_merged.hex +8857488ba6a69e366f0da229bbfc012a2ad291d3a88d9494247d600c10bb19b7 third_party/tock/target/thumbv7em-none-eabi/release/nrf52840_mdk_dfu.bin +04b94cd65bf83fa12030c4deaa831e0251f5f8b9684ec972d03a46e8f32e98b4 target/nrf52840_mdk_dfu_merged.hex +69dd51b947013b77e3577784384c935ed76930d1fb3ba46e9a5b6b5d71941057 target/tab/ctap2.tab diff --git a/reproducible/sample_crypto_data/opensk.key b/reproducible/sample_crypto_data/opensk.key new file mode 100644 index 0000000..5b68558 --- /dev/null +++ b/reproducible/sample_crypto_data/opensk.key @@ -0,0 +1,8 @@ +-----BEGIN EC PARAMETERS----- +BggqhkjOPQMBBw== +-----END EC PARAMETERS----- +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEICMfnFy7L3y5p2MOGezavAeS+noKYtT21mDcWllN7Y1zoAoGCCqGSM49 +AwEHoUQDQgAEhZflF2Fq4xmAofKOxG/0sx8bucdpJPRLR4HXArAFXJzdLF9ofkpn +gzsVWzTYFr+nNiyxySyJsdkH/qQv4rCV0A== +-----END EC PRIVATE KEY----- diff --git a/reproducible/sample_crypto_data/opensk_cert.pem b/reproducible/sample_crypto_data/opensk_cert.pem new file mode 100644 index 0000000..169321e --- /dev/null +++ b/reproducible/sample_crypto_data/opensk_cert.pem @@ -0,0 +1,9 @@ +-----BEGIN CERTIFICATE----- +MIIBPDCB4wIUTEbgPPL3tr2rLkI83EyzyQJQmYEwCgYIKoZIzj0EAwIwGzEZMBcG +A1UEAwwQR29vZ2xlIE9wZW5TSyBDQTAeFw0yMDA0MTQxNTM5MDRaFw0zMDA0MTQx +NTM5MDRaMCcxJTAjBgNVBAMMHEdvb2dsZSBPcGVuU0sgSGFja2VyIEVkaXRpb24w +WTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASFl+UXYWrjGYCh8o7Eb/SzHxu5x2kk +9EtHgdcCsAVcnN0sX2h+SmeDOxVbNNgWv6c2LLHJLImx2Qf+pC/isJXQMAoGCCqG +SM49BAMCA0gAMEUCIBKkHijpTbjlPDv3oFw/nW/ta8jEMhY8iNCBp9N0+NNYAiEA +ywzrGpmc0reEUFCGHBBdvC2E2SxIlvaefz7umT8ajy4= +-----END CERTIFICATE----- diff --git a/setup.sh b/setup.sh index 439003b..493297f 100755 --- a/setup.sh +++ b/setup.sh @@ -90,4 +90,4 @@ pip3 install --user --upgrade 'tockloader~=1.4' six intelhex rustup target add thumbv7em-none-eabi # Install dependency to create applications. -cargo install elf2tab +cargo install elf2tab --version 0.5.0 diff --git a/src/ctap/data_formats.rs b/src/ctap/data_formats.rs index a41efa6..c10815a 100644 --- a/src/ctap/data_formats.rs +++ b/src/ctap/data_formats.rs @@ -462,6 +462,9 @@ impl TryFrom<&cbor::Value> for CredentialProtectionPolicy { } // https://www.w3.org/TR/webauthn/#public-key-credential-source +// +// Note that we only use the WebAuthn definition as an example. This data-structure is not specified +// by FIDO. In particular we may choose how we serialize and deserialize it. #[derive(Clone)] #[cfg_attr(test, derive(PartialEq))] #[cfg_attr(any(test, feature = "debug_ctap"), derive(Debug))] @@ -477,30 +480,40 @@ pub struct PublicKeyCredentialSource { pub cred_protect_policy: Option, } +// We serialize credentials for the persistent storage using CBOR maps. Each field of a credential +// is associated with a unique tag, implemented with a CBOR unsigned key. +enum PublicKeyCredentialSourceField { + CredentialId = 0, + PrivateKey = 1, + RpId = 2, + UserHandle = 3, + OtherUi = 4, + CredRandom = 5, + CredProtectPolicy = 6, + // When a field is removed, its tag should be reserved and not used for new fields. We document + // those reserved tags below. + // Reserved tags: none. +} + +impl From for cbor::KeyType { + fn from(field: PublicKeyCredentialSourceField) -> cbor::KeyType { + (field as u64).into() + } +} + impl From for cbor::Value { fn from(credential: PublicKeyCredentialSource) -> cbor::Value { + use PublicKeyCredentialSourceField::*; let mut private_key = [0u8; 32]; credential.private_key.to_bytes(&mut private_key); - let other_ui = match credential.other_ui { - None => cbor_null!(), - Some(other_ui) => cbor_text!(other_ui), - }; - let cred_random = match credential.cred_random { - None => cbor_null!(), - Some(cred_random) => cbor_bytes!(cred_random), - }; - let cred_protect_policy = match credential.cred_protect_policy { - None => cbor_null!(), - Some(cred_protect_policy) => cbor_int!(cred_protect_policy as i64), - }; - cbor_array! { - credential.credential_id, - private_key, - credential.rp_id, - credential.user_handle, - other_ui, - cred_random, - cred_protect_policy, + cbor_map_options! { + CredentialId => Some(credential.credential_id), + PrivateKey => Some(private_key.to_vec()), + RpId => Some(credential.rp_id), + UserHandle => Some(credential.user_handle), + OtherUi => credential.other_ui, + CredRandom => credential.cred_random + CredProtectPolicy => credential.cred_protect_policy.map(|p| p as i64) } } } @@ -508,34 +521,40 @@ impl From for cbor::Value { impl TryFrom for PublicKeyCredentialSource { type Error = Ctap2StatusCode; - fn try_from(cbor_value: cbor::Value) -> Result { - use cbor::{SimpleValue, Value}; - - let fields = read_array(&cbor_value)?; - if fields.len() != 7 { - return Err(Ctap2StatusCode::CTAP2_ERR_INVALID_CBOR); - } - let credential_id = read_byte_string(&fields[0])?; - let private_key = read_byte_string(&fields[1])?; + fn try_from(cbor_value: cbor::Value) -> Result { + use PublicKeyCredentialSourceField::*; + let mut map = extract_map(cbor_value)?; + let credential_id = extract_byte_string(ok_or_missing(map.remove(&CredentialId.into()))?)?; + let private_key = extract_byte_string(ok_or_missing(map.remove(&PrivateKey.into()))?)?; if private_key.len() != 32 { return Err(Ctap2StatusCode::CTAP2_ERR_INVALID_CBOR); } let private_key = ecdsa::SecKey::from_bytes(array_ref!(private_key, 0, 32)) .ok_or(Ctap2StatusCode::CTAP2_ERR_INVALID_CBOR)?; - let rp_id = read_text_string(&fields[2])?; - let user_handle = read_byte_string(&fields[3])?; - let other_ui = match &fields[4] { - Value::Simple(SimpleValue::NullValue) => None, - cbor_value => Some(read_text_string(cbor_value)?), - }; - let cred_random = match &fields[5] { - Value::Simple(SimpleValue::NullValue) => None, - cbor_value => Some(read_byte_string(cbor_value)?), - }; - let cred_protect_policy = match &fields[6] { - Value::Simple(SimpleValue::NullValue) => None, - cbor_value => Some(CredentialProtectionPolicy::try_from(cbor_value)?), - }; + let rp_id = extract_text_string(ok_or_missing(map.remove(&RpId.into()))?)?; + let user_handle = extract_byte_string(ok_or_missing(map.remove(&UserHandle.into()))?)?; + let other_ui = map + .remove(&OtherUi.into()) + .map(extract_text_string) + .transpose()?; + let cred_random = map + .remove(&CredRandom.into()) + .map(extract_byte_string) + .transpose()?; + let cred_protect_policy = map + .remove(&CredProtectPolicy.into()) + .map(CredentialProtectionPolicy::try_from) + .transpose()?; + // We don't return whether there were unknown fields in the CBOR value. This means that + // deserialization is not injective. In particular deserialization is only an inverse of + // serialization at a given version of OpenSK. This is not a problem because: + // 1. When a field is deprecated, its tag is reserved and never reused in future versions, + // including to be reintroduced with the same semantics. In other words, removing a field + // is permanent. + // 2. OpenSK is never used with a more recent version of the storage. In particular, OpenSK + // is never rolled-back. + // As a consequence, the unknown fields are only reserved fields and don't need to be + // preserved. Ok(PublicKeyCredentialSource { key_type: PublicKeyCredentialType::PublicKey, credential_id, @@ -701,6 +720,13 @@ pub fn read_byte_string(cbor_value: &cbor::Value) -> Result, Ctap2Status } } +fn extract_byte_string(cbor_value: cbor::Value) -> Result, Ctap2StatusCode> { + match cbor_value { + cbor::Value::KeyValue(cbor::KeyType::ByteString(byte_string)) => Ok(byte_string), + _ => Err(Ctap2StatusCode::CTAP2_ERR_CBOR_UNEXPECTED_TYPE), + } +} + pub(super) fn read_text_string(cbor_value: &cbor::Value) -> Result { match cbor_value { cbor::Value::KeyValue(cbor::KeyType::TextString(text_string)) => { @@ -710,6 +736,13 @@ pub(super) fn read_text_string(cbor_value: &cbor::Value) -> Result Result { + match cbor_value { + cbor::Value::KeyValue(cbor::KeyType::TextString(text_string)) => Ok(text_string), + _ => Err(Ctap2StatusCode::CTAP2_ERR_CBOR_UNEXPECTED_TYPE), + } +} + pub(super) fn read_array(cbor_value: &cbor::Value) -> Result<&Vec, Ctap2StatusCode> { match cbor_value { cbor::Value::Array(array) => Ok(array), @@ -726,6 +759,15 @@ pub(super) fn read_map( } } +fn extract_map( + cbor_value: cbor::Value, +) -> Result, Ctap2StatusCode> { + match cbor_value { + cbor::Value::Map(map) => Ok(map), + _ => Err(Ctap2StatusCode::CTAP2_ERR_CBOR_UNEXPECTED_TYPE), + } +} + pub(super) fn read_bool(cbor_value: &cbor::Value) -> Result { match cbor_value { cbor::Value::Simple(cbor::SimpleValue::FalseValue) => Ok(false), @@ -734,9 +776,7 @@ pub(super) fn read_bool(cbor_value: &cbor::Value) -> Result, -) -> Result<&cbor::Value, Ctap2StatusCode> { +pub(super) fn ok_or_missing(value_option: Option) -> Result { value_option.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER) } diff --git a/src/ctap/storage.rs b/src/ctap/storage.rs index 1dd0213..4e33ba1 100644 --- a/src/ctap/storage.rs +++ b/src/ctap/storage.rs @@ -133,17 +133,6 @@ pub struct PersistentStore { store: embedded_flash::Store, } -#[cfg(feature = "ram_storage")] -const PAGE_SIZE: usize = 0x100; -#[cfg(not(feature = "ram_storage"))] -const PAGE_SIZE: usize = 0x1000; - -const STORE_SIZE: usize = NUM_PAGES * PAGE_SIZE; - -#[cfg(not(any(test, feature = "ram_storage")))] -#[link_section = ".app_state"] -static STORE: [u8; STORE_SIZE] = [0xff; STORE_SIZE]; - impl PersistentStore { /// Gives access to the persistent store. /// @@ -164,19 +153,16 @@ impl PersistentStore { #[cfg(not(any(test, feature = "ram_storage")))] fn new_prod_storage() -> Storage { - let store = unsafe { - // Safety: The store cannot alias because this function is called only once. - core::slice::from_raw_parts_mut(STORE.as_ptr() as *mut u8, STORE_SIZE) - }; - unsafe { - // Safety: The store is in a writeable flash region. - Storage::new(store).unwrap() - } + Storage::new(NUM_PAGES).unwrap() } #[cfg(any(test, feature = "ram_storage"))] fn new_test_storage() -> Storage { - let store = vec![0xff; STORE_SIZE].into_boxed_slice(); + #[cfg(not(test))] + const PAGE_SIZE: usize = 0x100; + #[cfg(test)] + const PAGE_SIZE: usize = 0x1000; + let store = vec![0xff; NUM_PAGES * PAGE_SIZE].into_boxed_slice(); let options = embedded_flash::BufferOptions { word_size: 4, page_size: PAGE_SIZE, diff --git a/src/embedded_flash/syscall.rs b/src/embedded_flash/syscall.rs index 7fca17a..fd5e738 100644 --- a/src/embedded_flash/syscall.rs +++ b/src/embedded_flash/syscall.rs @@ -13,6 +13,7 @@ // limitations under the License. use super::{Index, Storage, StorageError, StorageResult}; +use alloc::vec::Vec; use libtock::syscalls; const DRIVER_NUMBER: usize = 0x50003; @@ -33,8 +34,23 @@ mod allow_nr { pub const WRITE_SLICE: usize = 0; } -fn get_info(nr: usize) -> StorageResult { - let code = unsafe { syscalls::command(DRIVER_NUMBER, command_nr::GET_INFO, nr, 0) }; +mod memop_nr { + pub const STORAGE_CNT: u32 = 12; + pub const STORAGE_PTR: u32 = 13; + pub const STORAGE_LEN: u32 = 14; +} + +fn get_info(nr: usize, arg: usize) -> StorageResult { + let code = unsafe { syscalls::command(DRIVER_NUMBER, command_nr::GET_INFO, nr, arg) }; + if code < 0 { + Err(StorageError::KernelError { code }) + } else { + Ok(code as usize) + } +} + +fn memop(nr: u32, arg: usize) -> StorageResult { + let code = unsafe { syscalls::memop(nr, arg) }; if code < 0 { Err(StorageError::KernelError { code }) } else { @@ -45,70 +61,56 @@ fn get_info(nr: usize) -> StorageResult { pub struct SyscallStorage { word_size: usize, page_size: usize, + num_pages: usize, max_word_writes: usize, max_page_erases: usize, - storage: &'static mut [u8], + storage_locations: Vec<&'static [u8]>, } impl SyscallStorage { /// Provides access to the embedded flash if available. /// - /// # Safety - /// - /// The `storage` must be in a writeable flash region. - /// /// # Errors /// /// Returns `BadFlash` if any of the following conditions do not hold: - /// - The word size is not a power of two. - /// - The page size is not a power of two. - /// - The page size is not a multiple of the word size. + /// - The word size is a power of two. + /// - The page size is a power of two. + /// - The page size is a multiple of the word size. + /// - The storage is page-aligned. /// - /// Returns `NotAligned` if any of the following conditions do not hold: - /// - `storage` is page-aligned. - /// - `storage.len()` is a multiple of the page size. - /// - /// # Examples - /// - /// ```rust - /// # extern crate ctap2; - /// # use ctap2::embedded_flash::SyscallStorage; - /// # use ctap2::embedded_flash::StorageResult; - /// # const NUM_PAGES: usize = 1; - /// # const PAGE_SIZE: usize = 1; - /// #[link_section = ".app_state"] - /// static mut STORAGE: [u8; NUM_PAGES * PAGE_SIZE] = [0xff; NUM_PAGES * PAGE_SIZE]; - /// # fn foo() -> StorageResult { - /// // This is safe because this is the only use of `STORAGE` in the whole program and this is - /// // called only once. - /// unsafe { SyscallStorage::new(&mut STORAGE) } - /// # } - /// ``` - pub unsafe fn new(storage: &'static mut [u8]) -> StorageResult { - let word_size = get_info(command_nr::get_info_nr::WORD_SIZE)?; - let page_size = get_info(command_nr::get_info_nr::PAGE_SIZE)?; - let max_word_writes = get_info(command_nr::get_info_nr::MAX_WORD_WRITES)?; - let max_page_erases = get_info(command_nr::get_info_nr::MAX_PAGE_ERASES)?; - if !word_size.is_power_of_two() || !page_size.is_power_of_two() { - return Err(StorageError::BadFlash); - } - let syscall = SyscallStorage { - word_size, - page_size, - max_word_writes, - max_page_erases, - storage, + /// Returns `OutOfBounds` the number of pages does not fit in the storage. + pub fn new(mut num_pages: usize) -> StorageResult { + let mut syscall = SyscallStorage { + word_size: get_info(command_nr::get_info_nr::WORD_SIZE, 0)?, + page_size: get_info(command_nr::get_info_nr::PAGE_SIZE, 0)?, + num_pages, + max_word_writes: get_info(command_nr::get_info_nr::MAX_WORD_WRITES, 0)?, + max_page_erases: get_info(command_nr::get_info_nr::MAX_PAGE_ERASES, 0)?, + storage_locations: Vec::new(), }; - if !syscall.is_word_aligned(page_size) { + if !syscall.word_size.is_power_of_two() + || !syscall.page_size.is_power_of_two() + || !syscall.is_word_aligned(syscall.page_size) + { return Err(StorageError::BadFlash); } - if syscall.is_page_aligned(syscall.storage.as_ptr() as usize) - && syscall.is_page_aligned(syscall.storage.len()) - { - Ok(syscall) - } else { - Err(StorageError::NotAligned) + for i in 0..memop(memop_nr::STORAGE_CNT, 0)? { + let storage_ptr = memop(memop_nr::STORAGE_PTR, i)?; + let max_storage_len = memop(memop_nr::STORAGE_LEN, i)?; + if !syscall.is_page_aligned(storage_ptr) || !syscall.is_page_aligned(max_storage_len) { + return Err(StorageError::BadFlash); + } + let storage_len = core::cmp::min(num_pages * syscall.page_size, max_storage_len); + num_pages -= storage_len / syscall.page_size; + syscall + .storage_locations + .push(unsafe { core::slice::from_raw_parts(storage_ptr as *mut u8, storage_len) }); } + if num_pages > 0 { + // The storage locations don't have enough pages. + return Err(StorageError::OutOfBounds); + } + Ok(syscall) } fn is_word_aligned(&self, x: usize) -> bool { @@ -130,7 +132,7 @@ impl Storage for SyscallStorage { } fn num_pages(&self) -> usize { - self.storage.len() / self.page_size + self.num_pages } fn max_word_writes(&self) -> usize { @@ -142,14 +144,15 @@ impl Storage for SyscallStorage { } fn read_slice(&self, index: Index, length: usize) -> StorageResult<&[u8]> { - Ok(&self.storage[index.range(length, self)?]) + let start = index.range(length, self)?.start; + find_slice(&self.storage_locations, start, length) } fn write_slice(&mut self, index: Index, value: &[u8]) -> StorageResult<()> { if !self.is_word_aligned(index.byte) || !self.is_word_aligned(value.len()) { return Err(StorageError::NotAligned); } - let range = index.range(value.len(), self)?; + let ptr = self.read_slice(index, value.len())?.as_ptr() as usize; let code = unsafe { syscalls::allow_ptr( DRIVER_NUMBER, @@ -163,14 +166,8 @@ impl Storage for SyscallStorage { if code < 0 { return Err(StorageError::KernelError { code }); } - let code = unsafe { - syscalls::command( - DRIVER_NUMBER, - command_nr::WRITE_SLICE, - self.storage[range].as_ptr() as usize, - 0, - ) - }; + let code = + unsafe { syscalls::command(DRIVER_NUMBER, command_nr::WRITE_SLICE, ptr, value.len()) }; if code < 0 { return Err(StorageError::KernelError { code }); } @@ -178,18 +175,59 @@ impl Storage for SyscallStorage { } fn erase_page(&mut self, page: usize) -> StorageResult<()> { - let range = Index { page, byte: 0 }.range(self.page_size(), self)?; - let code = unsafe { - syscalls::command( - DRIVER_NUMBER, - command_nr::ERASE_PAGE, - self.storage[range].as_ptr() as usize, - 0, - ) - }; + let index = Index { page, byte: 0 }; + let length = self.page_size(); + let ptr = self.read_slice(index, length)?.as_ptr() as usize; + let code = unsafe { syscalls::command(DRIVER_NUMBER, command_nr::ERASE_PAGE, ptr, length) }; if code < 0 { return Err(StorageError::KernelError { code }); } Ok(()) } } + +fn find_slice<'a>( + slices: &'a [&'a [u8]], + mut start: usize, + length: usize, +) -> StorageResult<&'a [u8]> { + for slice in slices { + if start >= slice.len() { + start -= slice.len(); + continue; + } + if start + length > slice.len() { + break; + } + return Ok(&slice[start..][..length]); + } + Err(StorageError::OutOfBounds) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn find_slice_ok() { + assert_eq!( + find_slice(&[&[1, 2, 3, 4]], 0, 4).ok(), + Some(&[1u8, 2, 3, 4] as &[u8]) + ); + assert_eq!( + find_slice(&[&[1, 2, 3, 4], &[5, 6]], 1, 2).ok(), + Some(&[2u8, 3] as &[u8]) + ); + assert_eq!( + find_slice(&[&[1, 2, 3, 4], &[5, 6]], 4, 2).ok(), + Some(&[5u8, 6] as &[u8]) + ); + assert_eq!( + find_slice(&[&[1, 2, 3, 4], &[5, 6]], 4, 0).ok(), + Some(&[] as &[u8]) + ); + assert!(find_slice(&[], 0, 1).is_err()); + assert!(find_slice(&[&[1, 2, 3, 4], &[5, 6]], 6, 0).is_err()); + assert!(find_slice(&[&[1, 2, 3, 4], &[5, 6]], 3, 2).is_err()); + } +}