From 5dfad296ae9bdcaf623aa7997b58bf25f54a622b Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Tue, 12 Sep 2023 10:03:01 +0800 Subject: [PATCH] xous: mark MemoryRange::as_slice and friends as unsafe Mark `MemoryRange::as_slice()` and `MemoryRange::as_slice_mut()` as unsafe. This is due to the fact that not all representable types can be cast to an arbitrary value. For example, if Process A sends random values to Process B, then Process B casts the memory to a slice of `bool`, then any values that are not 0 or 1 are undefined. Because these functions can leak UB into the program, they are marked as unsafe. This patch adds `unsafe {}` blocks to all instances where this function is called. Additionally, all instances have been checked to verify that they do not cast to any invalid types -- most use `u8` or `u32`. Additionally, the long-deprecated `MemoryRange::from_parts()` call was removed, since that causes UB without being marked as unsafe. Signed-off-by: Sean Cross --- apps/transientdisk/src/flash_drive.rs | 17 ++-- kernel/src/services.rs | 2 +- services/dns/src/main.rs | 4 +- services/early_settings/src/main.rs | 6 +- .../graphics-server/src/backend/betrusted.rs | 9 +- services/graphics-server/src/main.rs | 9 +- services/net/src/main.rs | 20 ++--- services/net/src/std_glue.rs | 6 +- services/net/src/std_tcplistener.rs | 8 +- services/net/src/std_tcpstream.rs | 12 +-- services/net/src/std_udp.rs | 18 ++-- services/pddb/src/backend/hosted.rs | 8 +- services/pddb/src/backend/hw.rs | 53 ++++++------ services/pddb/src/lib.rs | 12 ++- services/pddb/src/libstd/mod.rs | 33 +++++--- services/pddb/src/main.rs | 3 +- services/root-keys/src/implementation.rs | 54 ++++++------ services/shellchat/src/cmds/test.rs | 4 +- services/status/src/ecup.rs | 6 +- xous-rs/src/arch/hosted/mod.rs | 2 +- xous-rs/src/arch/riscv/process.rs | 2 +- xous-rs/src/definitions.rs | 78 +---------------- xous-rs/src/definitions/memoryrange.rs | 83 +++++++++++++++++++ xous-rs/src/lib.rs | 2 +- 24 files changed, 245 insertions(+), 206 deletions(-) create mode 100644 xous-rs/src/definitions/memoryrange.rs diff --git a/apps/transientdisk/src/flash_drive.rs b/apps/transientdisk/src/flash_drive.rs index 0dc3beed2..b070a27d8 100644 --- a/apps/transientdisk/src/flash_drive.rs +++ b/apps/transientdisk/src/flash_drive.rs @@ -25,8 +25,9 @@ impl FlashDrive { ) .unwrap(); - // initialize backing slice with bogus data - let backing_slice: &mut [u32] = backing.as_slice_mut(); + // initialize backing slice with bogus data. Safety: all `[u32]` + // values are valid + let backing_slice: &mut [u32] = unsafe { backing.as_slice_mut() }; for (index, d) in backing_slice.iter_mut().enumerate() { *d = index as u32; } @@ -44,7 +45,8 @@ impl FlashDrive { .memory_message_mut() .expect("incorrect message type received"); let lba = body.offset.map(|v| v.get()).unwrap_or_default(); - let data = body.buf.as_slice_mut::(); + // Safety: all values of `[u32]` are valid + let data = unsafe { body.buf.as_slice_mut::() }; self.read_inner(lba, data); } @@ -55,7 +57,8 @@ impl FlashDrive { .memory_message_mut() .expect("incorrect message type received"); let lba = body.offset.map(|v| v.get()).unwrap_or_default(); - let data = body.buf.as_slice_mut::(); + // Safety: all values of `[u32]` are valid + let data = unsafe { body.buf.as_slice_mut::() }; self.write_inner(lba, data); } @@ -67,7 +70,8 @@ impl FlashDrive { impl FlashDrive { fn read_inner(&mut self, lba: usize, data: &mut [u8]) { - let backing_slice: &[u8] = self.memory.as_slice(); + // Safety: all values of `[u8]` are valid + let backing_slice: &[u8] = unsafe { self.memory.as_slice() }; let rawdata = &backing_slice[lba * self.block_size..(lba + 1) * self.block_size]; @@ -75,7 +79,8 @@ impl FlashDrive { } fn write_inner(&mut self, lba: usize, data: &mut [u8]) { - let backing_slice: &mut [u8] = self.memory.as_slice_mut(); + // Safety: all values of `[u8]` are valid + let backing_slice: &mut [u8] = unsafe { self.memory.as_slice_mut() }; backing_slice[lba * self.block_size..(lba + 1) * self.block_size] .copy_from_slice(&data[..self.block_size]); } diff --git a/kernel/src/services.rs b/kernel/src/services.rs index b1449046e..acd828aed 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -1645,7 +1645,7 @@ impl SystemServices { // buf: MemoryRange, ) -> Result<*mut usize, xous_kernel::Error> { let buf = unsafe { MemoryRange::new(src_virt as usize, len) }?; - let buf = buf.as_slice(); + let buf = unsafe { buf.as_slice() }; let current_pid = self.current_pid(); { let target_process = self.get_process(dest_pid)?; diff --git a/services/dns/src/main.rs b/services/dns/src/main.rs index 9090fdd44..565562f42 100644 --- a/services/dns/src/main.rs +++ b/services/dns/src/main.rs @@ -427,7 +427,7 @@ fn name_from_msg(env: &xous::MessageEnvelope) -> Result<&str, NameConversionErro fn fill_response(mut env: xous::MessageEnvelope, entries: &HashMap) -> Option<()> { let mem = env.body.memory_message_mut()?; - let s: &mut [u8] = mem.buf.as_slice_mut(); + let s: &mut [u8] = unsafe { mem.buf.as_slice_mut() }; let mut i = s.iter_mut(); // First tag = 1 for "Error" -- we'll fill this in at the end when it's successful @@ -472,7 +472,7 @@ fn fill_response(mut env: xous::MessageEnvelope, entries: &HashMap) fn fill_error(mut env: xous::MessageEnvelope, code: DnsResponseCode) -> Option<()> { let mem = env.body.memory_message_mut()?; - let s: &mut [u8] = mem.buf.as_slice_mut(); + let s: &mut [u8] = unsafe { mem.buf.as_slice_mut() }; let mut i = s.iter_mut(); *i.next()? = 1; diff --git a/services/early_settings/src/main.rs b/services/early_settings/src/main.rs index 934afc34a..1bc17271f 100644 --- a/services/early_settings/src/main.rs +++ b/services/early_settings/src/main.rs @@ -43,7 +43,8 @@ impl State { None => return, }; - let settings: &[u8] = settings.as_slice(); + // Safety: all values of `[u8]` are valid + let settings: &[u8] = unsafe { settings.as_slice() }; let new_data_u32 = u32::from_le_bytes(data.try_into().unwrap()); @@ -62,7 +63,8 @@ impl State { None => return 0, }; - let settings: &[u8] = settings.as_slice(); + // Safety: all values of `[u8]` are valid + let settings: &[u8] = unsafe { settings.as_slice() }; u32::from_le_bytes(settings[slot.range()].try_into().unwrap()) } diff --git a/services/graphics-server/src/backend/betrusted.rs b/services/graphics-server/src/backend/betrusted.rs index 95ddc2dca..3324b81f6 100644 --- a/services/graphics-server/src/backend/betrusted.rs +++ b/services/graphics-server/src/backend/betrusted.rs @@ -123,7 +123,8 @@ impl XousDisplay { } } pub fn pop(&mut self) { - let fb: &mut [u32] = self.fb.as_slice_mut(); + // Safety: `u32` contains no undefined values + let fb: &mut [u32] = unsafe { self.fb.as_slice_mut() }; // skip copying the status bar, so that the status info is not overwritten by the pop. // this is "fixed" at 32 pixels high (2 * Cjk glyph height hint) per line 79 in gam/src/main.rs fb[FB_WIDTH_WORDS * 32..FB_SIZE].copy_from_slice(&self.srfb[FB_WIDTH_WORDS * 32..FB_SIZE]); @@ -184,7 +185,8 @@ impl XousDisplay { } pub fn resume(&mut self) { self.susres.resume(); - let fb: &mut [u32] = self.fb.as_slice_mut(); + // Safety: `u32` contains no undefined values + let fb: &mut [u32] = unsafe { self.fb.as_slice_mut() }; fb[..FB_SIZE].copy_from_slice(&self.srfb); self.redraw(); @@ -241,7 +243,8 @@ impl XousDisplay { } pub fn as_slice(&self) -> &[u32] { - &self.fb.as_slice::()[..FB_SIZE] + // Safety: all values of `[u32]` are valid + unsafe { &self.fb.as_slice::()[..FB_SIZE] } } /// Beneath this line are pure-HAL layer, and should not be user-visible diff --git a/services/graphics-server/src/main.rs b/services/graphics-server/src/main.rs index 2afc83662..b0a5ca0ef 100644 --- a/services/graphics-server/src/main.rs +++ b/services/graphics-server/src/main.rs @@ -488,7 +488,8 @@ fn wrapped_main(main_thread_token: backend::MainThreadToken) -> ! { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; //let mut bulkread = buf.as_flat::().unwrap(); // try to skip the copy/init step by using a persistent structure - let fontslice = fontregion.as_slice::(); + // Safety: `u8` contains no undefined values + let fontslice = unsafe { fontregion.as_slice::() }; assert!(fontlen <= fontslice.len() as u32); if bulkread.from_offset >= fontlen { log::error!( @@ -520,7 +521,8 @@ fn wrapped_main(main_thread_token: backend::MainThreadToken) -> ! { ((backend::FB_SIZE * 4) + 4096) & !4095, xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map stash frame buffer"); - let stash = &mut stashmem.as_slice_mut()[..backend::FB_SIZE]; + // Safety: `u8` contains no undefined values + let stash = unsafe { &mut stashmem.as_slice_mut()[..backend::FB_SIZE] }; for (&src, dst) in display.as_slice().iter().zip(stash.iter_mut()) { *dst = src; } @@ -535,7 +537,8 @@ fn wrapped_main(main_thread_token: backend::MainThreadToken) -> ! { ((backend::FB_SIZE * 4) + 4096) & !4095, xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map stash frame buffer"); - let testpat = &mut testmem.as_slice_mut()[..backend::FB_SIZE]; + // Safety: `u8` contains no undefined values + let testpat = unsafe { &mut testmem.as_slice_mut()[..backend::FB_SIZE] }; const DWELL: usize = 1000; while ticktimer.elapsed_ms() - start_time < duration as u64 { // all black diff --git a/services/net/src/main.rs b/services/net/src/main.rs index 76ff5264f..1ae9f004a 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -813,7 +813,7 @@ fn main() -> ! { Some(body) => { // u32::MAX indicates a zero-length receive body.valid = xous::MemorySize::new(u32::MAX as usize); - let response_data = body.buf.as_slice_mut::(); + let response_data = unsafe { body.buf.as_slice_mut::() }; response_data[0] = 0; response_data[1] = 0; }, @@ -894,7 +894,7 @@ fn main() -> ! { { let socket = iface.get_socket::(*connection); body.valid = xous::MemorySize::new( - write_address(socket.local_endpoint().addr, body.buf.as_slice_mut()) + write_address(socket.local_endpoint().addr, unsafe { body.buf.as_slice_mut() }) .unwrap_or_default(), ); } else { @@ -1089,7 +1089,7 @@ fn main() -> ! { iface.get_socket::(handle).close(); iface.remove_socket(handle); if let Some(response) = msg.body.memory_message_mut() { - response.buf.as_slice_mut::()[0] = 0; + unsafe { response.buf.as_slice_mut::()[0] = 0 }; } else if !msg.body.has_memory() && msg.body.is_blocking() { xous::return_scalar(msg.sender, 0).ok(); } @@ -1411,7 +1411,7 @@ fn main() -> ! { } else { 0 }; - match socket.recv_slice(&mut body.buf.as_slice_mut()[..buflen]) { + match socket.recv_slice(unsafe { &mut body.buf.as_slice_mut()[..buflen] }) { Ok(count) => { log::debug!("rxrcv of {}", count); body.valid = xous::MemorySize::new(count); @@ -1484,7 +1484,7 @@ fn main() -> ! { } else { 0 }; - match socket.peek_slice(&mut body.buf.as_slice_mut()[..buflen]) { + match socket.peek_slice(unsafe { &mut body.buf.as_slice_mut()[..buflen] }) { Ok(count) => { log::debug!("peekrcv of {}", count); body.valid = xous::MemorySize::new(count); @@ -1538,7 +1538,7 @@ fn main() -> ! { let body = env.body.memory_message_mut().unwrap(); // Perform the transfer let sent_octets = { - let data = body.buf.as_slice::(); + let data = unsafe { body.buf.as_slice::() }; let length = body .valid .map(|v| { @@ -1561,7 +1561,7 @@ fn main() -> ! { }; log::trace!("sent {}", sent_octets); - let response_data = body.buf.as_slice_mut::(); + let response_data = unsafe { body.buf.as_slice_mut::() }; response_data[0] = 0; response_data[1] = sent_octets as u32; } @@ -1588,7 +1588,7 @@ fn main() -> ! { } }; let body = env.body.memory_message_mut().unwrap(); - let buf = body.buf.as_slice_mut::(); + let buf = unsafe { body.buf.as_slice_mut::() }; tcp_accept_success(buf, fd as u16, ep); } @@ -1636,7 +1636,7 @@ fn main() -> ! { Ok((data, endpoint)) => { udp_rx_success( // unwrap is safe here because the message was type-checked prior to insertion into the waiting queue - msg.body.memory_message_mut().unwrap().buf.as_slice_mut(), + unsafe { msg.body.memory_message_mut().unwrap().buf.as_slice_mut() }, data, *endpoint // have to duplicate the code between peek and recv because of this type difference ); @@ -1652,7 +1652,7 @@ fn main() -> ! { log::debug!("netpump udp rx"); udp_rx_success( // unwrap is safe here because the message was type-checked prior to insertion into the waiting queue - msg.body.memory_message_mut().unwrap().buf.as_slice_mut(), + unsafe { msg.body.memory_message_mut().unwrap().buf.as_slice_mut() }, data, endpoint ); diff --git a/services/net/src/std_glue.rs b/services/net/src/std_glue.rs index b81516332..5deb96f75 100644 --- a/services/net/src/std_glue.rs +++ b/services/net/src/std_glue.rs @@ -61,7 +61,7 @@ pub(crate) fn respond_with_error(mut env: xous::MessageEnvelope, code: NetError) }; body.valid = None; - let s: &mut [u8] = body.buf.as_slice_mut(); + let s: &mut [u8] = unsafe { body.buf.as_slice_mut() }; let mut i = s.iter_mut(); // Duplicate error to ensure it's seen as an error regardless of byte order/return type @@ -85,7 +85,7 @@ pub(crate) fn respond_with_connected( remote_port: u16, ) { let body = env.body.memory_message_mut().unwrap(); - let bfr = body.buf.as_slice_mut::(); + let bfr = unsafe { body.buf.as_slice_mut::() }; log::debug!("successfully connected: {}", idx); bfr[0] = 0; @@ -113,4 +113,4 @@ pub(crate) fn insert_or_append(arr: &mut Vec>, val: T) -> usize { arr.push(Some(val)); idx } -} \ No newline at end of file +} diff --git a/services/net/src/std_tcplistener.rs b/services/net/src/std_tcplistener.rs index 2c56cdbba..9cd829e94 100644 --- a/services/net/src/std_tcplistener.rs +++ b/services/net/src/std_tcplistener.rs @@ -18,7 +18,7 @@ pub(crate) fn std_tcp_listen( } }; - let bytes = body.buf.as_slice::(); + let bytes = unsafe { body.buf.as_slice::() }; let mut local_port = u16::from_le_bytes([bytes[0], bytes[1]]); let mut retry_local_port = false; if local_port == 0 { @@ -83,7 +83,7 @@ pub(crate) fn std_tcp_listen( let fd = insert_or_append(our_sockets, handle) as u8; let body = msg.body.memory_message_mut().unwrap(); - let bfr = body.buf.as_slice_mut::(); + let bfr = unsafe { body.buf.as_slice_mut::() }; log::debug!("successfully connected: {} -> {:?}:{}", fd, address, local_port); bfr[0] = 0; bfr[1] = fd; @@ -119,14 +119,14 @@ pub(crate) fn std_tcp_accept( } }; - let args = body.buf.as_slice::(); + let args = unsafe { body.buf.as_slice::() }; let nonblocking = args[0] == 0; let socket = iface.get_socket::(*handle); if socket.is_active() { log::debug!("accept did not block; immediately returning TcpSocket"); - let buf = body.buf.as_slice_mut::(); + let buf = unsafe { body.buf.as_slice_mut::() }; tcp_server_remote_close_poll.push(*handle); tcp_accept_success(buf, fd as u16, socket.remote_endpoint()); return; diff --git a/services/net/src/std_tcpstream.rs b/services/net/src/std_tcpstream.rs index 0cd84880c..6d79de4ee 100644 --- a/services/net/src/std_tcpstream.rs +++ b/services/net/src/std_tcpstream.rs @@ -27,7 +27,7 @@ pub(crate) fn std_tcp_connect( } }; - let bytes = body.buf.as_slice::(); + let bytes = unsafe { body.buf.as_slice::() }; let remote_port = u16::from_le_bytes([bytes[0], bytes[1]]); let timeout_ms = NonZeroU64::new(u64::from_le_bytes(bytes[2..10].try_into().unwrap())); let address = match parse_address(&bytes[10..]) { @@ -120,7 +120,7 @@ pub(crate) fn std_tcp_tx( // Perform the transfer let sent_octets = { - let data = body.buf.as_slice::(); + let data = unsafe { body.buf.as_slice::() }; let length = body .valid .map(|v| { @@ -142,7 +142,7 @@ pub(crate) fn std_tcp_tx( }; log::trace!("sent {}", sent_octets); - let response_data = body.buf.as_slice_mut::(); + let response_data = unsafe { body.buf.as_slice_mut::() }; response_data[0] = 0; response_data[1] = sent_octets as u32; } @@ -186,7 +186,7 @@ pub(crate) fn std_tcp_rx( } else { 0 }; - match socket.recv_slice(&mut body.buf.as_slice_mut()[..buflen]) { + match socket.recv_slice(unsafe { &mut body.buf.as_slice_mut()[..buflen] }) { Ok(bytes) => { // it's actually valid to receive 0 bytes, but the encoding of this field doesn't allow it. // so, `None` is abused to represent the value of "0" bytes, which is what is naturally returned @@ -263,7 +263,7 @@ pub(crate) fn std_tcp_peek( } else { 0 }; - match socket.peek_slice(&mut body.buf.as_slice_mut()[..buflen]) { + match socket.peek_slice(unsafe { &mut body.buf.as_slice_mut()[..buflen] }) { Ok(bytes) => { // it's actually valid to receive 0 bytes, but the encoding of this field doesn't allow it. // so, `None` is abused to represent the value of "0" bytes, which is what is naturally returned @@ -304,4 +304,4 @@ pub(crate) fn std_tcp_can_close(tx_waiting: &Vec>, handle: } } true -} \ No newline at end of file +} diff --git a/services/net/src/std_udp.rs b/services/net/src/std_udp.rs index cf721095f..0f7865acb 100644 --- a/services/net/src/std_udp.rs +++ b/services/net/src/std_udp.rs @@ -25,7 +25,7 @@ pub(crate) fn std_udp_bind( } }; - let bytes = body.buf.as_slice::(); + let bytes = unsafe { body.buf.as_slice::() }; let local_port = u16::from_le_bytes([bytes[0], bytes[1]]); let address = match parse_address(&bytes[2..]) { Some(addr) => addr, @@ -62,7 +62,7 @@ pub(crate) fn std_udp_bind( let idx = insert_or_append(our_sockets, handle) as u8; let body = msg.body.memory_message_mut().unwrap(); - let bfr = body.buf.as_slice_mut::(); + let bfr = unsafe { body.buf.as_slice_mut::() }; log::trace!("successfully connected: {} -> {:?}:{}", idx, address, local_port); bfr[0] = 0; bfr[1] = idx; @@ -95,7 +95,7 @@ pub(crate) fn std_udp_rx( } }; - let args = body.buf.as_slice::(); + let args = unsafe { body.buf.as_slice::() }; let nonblocking = args[0] == 0; let expiry = if !nonblocking { let to = u64::from_le_bytes(args[1..9].try_into().unwrap()); @@ -143,7 +143,7 @@ pub(crate) fn std_udp_rx( // difference in types means you can't do a pattern match assign to a common variable. match socket.peek() { Ok((data, endpoint)) => { - udp_rx_success(body.buf.as_slice_mut(), data, *endpoint); + udp_rx_success(unsafe { body.buf.as_slice_mut() }, data, *endpoint); } Err(e) => { log::error!("unable to receive: {:?}", e); @@ -154,7 +154,7 @@ pub(crate) fn std_udp_rx( match socket.recv() { Ok((data, endpoint)) => { log::debug!("immediate udp rx"); - udp_rx_success(body.buf.as_slice_mut(), data, endpoint); + udp_rx_success(unsafe { body.buf.as_slice_mut() }, data, endpoint); } Err(e) => { log::error!("unable to receive: {:?}", e); @@ -206,7 +206,7 @@ pub(crate) fn std_udp_tx( }; // unpack arguments - let bytes = body.buf.as_slice::(); + let bytes = unsafe { body.buf.as_slice::() }; let remote_port = u16::from_le_bytes([bytes[0], bytes[1]]); let address = match parse_address(&bytes[2..]) { Some(addr) => addr, @@ -247,7 +247,7 @@ pub(crate) fn std_udp_tx( } } match socket.send_slice(&bytes[21..21 + len as usize], IpEndpoint::new(address, remote_port)) { - Ok(_) => { + Ok(_) => unsafe { body.buf.as_slice_mut()[0] = 0; } Err(_e) => { @@ -304,10 +304,10 @@ pub(crate) fn std_failure(mut env: xous::MessageEnvelope, code: NetError) -> Opt }; body.valid = None; - let s: &mut [u8] = body.buf.as_slice_mut(); + let s: &mut [u8] = unsafe { body.buf.as_slice_mut() }; let mut i = s.iter_mut(); *i.next()? = 1; *i.next()? = code as u8; None -} \ No newline at end of file +} diff --git a/services/pddb/src/backend/hosted.rs b/services/pddb/src/backend/hosted.rs index c37425675..f3994b107 100644 --- a/services/pddb/src/backend/hosted.rs +++ b/services/pddb/src/backend/hosted.rs @@ -78,15 +78,13 @@ impl EmuStorage { EmuStorage { } } - pub fn as_slice(&self) -> &[T] { - unsafe { + pub unsafe fn as_slice(&self) -> &[T] { core::slice::from_raw_parts( flashmem().memory.as_ptr() as *const T, flashmem().memory.len() / core::mem::size_of::(), ) - } } - pub fn as_mut_slice(&mut self) -> &mut [u8] { + pub unsafe fn as_mut_slice(&mut self) -> &mut [u8] { flashmem().memory.as_mut_slice() } /// used to reset the storage for repeated test case generation @@ -146,4 +144,4 @@ impl HostedSpinor { flashmem().disk.write(&blank).expect("couldn't write PDDB"); Ok(()) } -} \ No newline at end of file +} diff --git a/services/pddb/src/backend/hw.rs b/services/pddb/src/backend/hw.rs index 395c8219a..d352b9b23 100644 --- a/services/pddb/src/backend/hw.rs +++ b/services/pddb/src/backend/hw.rs @@ -197,7 +197,8 @@ impl PddbOs { ) .expect("Couldn't map the PDDB memory range"); #[cfg(any(feature="precursor", feature="renode"))] - log::info!("pddb slice len: {}, PDDB_A_LEN: {}, raw len: {}", pddb.as_slice::().len(), PDDB_A_LEN, pddb.len()); // sanity check the PDDB size on init + // Safety: all u8 values are valid + log::info!("pddb slice len: {}, PDDB_A_LEN: {}, raw len: {}", unsafe { pddb.as_slice::().len() }, PDDB_A_LEN, pddb.len()); // sanity check the PDDB size on init // the mbbb is located one page off from the Page Table let key_phys_base = PageAlignedPa::from(size_of::()); @@ -376,7 +377,7 @@ impl PddbOs { // log::trace!("patch bef: {:x?}", &self.pddb_mr.as_slice::()[offset as usize + self.data_phys_base.as_usize()..offset as usize + self.data_phys_base.as_usize() + 48]); assert!(data.len() + offset as usize <= PDDB_A_LEN - self.data_phys_base.as_usize(), "attempt to store past disk boundary"); self.spinor.patch( - self.pddb_mr.as_slice(), + unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, &data, offset + self.data_phys_base.as_u32(), @@ -391,7 +392,7 @@ impl PddbOs { if let Some(mbbb) = self.mbbb_retrieve() { if let Some(erased_offset) = self.pt_find_erased_slot() { self.spinor.patch( - self.pddb_mr.as_slice(), + unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, &mbbb, self.pt_phys_base.as_u32() + erased_offset, @@ -407,7 +408,7 @@ impl PddbOs { // 3. copy the data to a local buffer let mut mbbb_page = [0u8; PAGE_SIZE]; for (&src, dst) in - self.pddb_mr.as_slice()[self.pt_phys_base.as_usize() + base_page..self.pt_phys_base.as_usize() + base_page + PAGE_SIZE].iter() + unsafe { self.pddb_mr.as_slice()[self.pt_phys_base.as_usize() + base_page..self.pt_phys_base.as_usize() + base_page + PAGE_SIZE].iter() } .zip(mbbb_page.iter_mut()) { *dst = src; } @@ -423,7 +424,7 @@ impl PddbOs { // 6. erase the original page area, thus making the MBBB the authorative location let blank = [0xffu8; PAGE_SIZE]; self.spinor.patch( - self.pddb_mr.as_slice(), + unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, &blank, self.pt_phys_base.as_u32() + base_page as u32, @@ -436,7 +437,7 @@ impl PddbOs { fn patch_pagetable_raw(&self, data: &[u8], offset: u32) { assert!(data.len() + offset as usize <= size_of::(), "attempt to patch past page table end"); self.spinor.patch( - self.pddb_mr.as_slice(), + unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, &data, self.pt_phys_base.as_u32() + offset, @@ -446,7 +447,7 @@ impl PddbOs { assert!(data.len() + offset as usize <= PAGE_SIZE, "attempt to burn key data that is outside the key region"); log::info!("patching keys area with {} bytes", data.len()); self.spinor.patch( - self.pddb_mr.as_slice(), + unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, data, self.key_phys_base.as_u32() + offset @@ -455,7 +456,7 @@ impl PddbOs { fn patch_mbbb(&self, data: &[u8], offset: u32) { assert!(data.len() + offset as usize <= PAGE_SIZE * MBBB_PAGES, "mbbb patch would go out of bounds"); self.spinor.patch( - self.pddb_mr.as_slice(), + unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, data, self.mbbb_phys_base.as_u32() + offset @@ -466,7 +467,7 @@ impl PddbOs { fn patch_fscb(&self, data: &[u8], offset: u32) { assert!(data.len() + offset as usize <= PAGE_SIZE * FSCB_PAGES, "fscb patch would go out of bounds"); self.spinor.patch( - self.pddb_mr.as_slice(), + unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, data, self.fscb_phys_base.as_u32() + offset @@ -497,7 +498,7 @@ impl PddbOs { /// This would want to be optimized or cached for a much larger filesystem. /// Returns the physical address of the erased slot as an offset from the pt_phys_base() fn pt_find_erased_slot(&self) -> Option { - let pt: &[u8] = &self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::()]; + let pt: &[u8] = unsafe { &self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::()] }; let blank = [0xffu8; aes::BLOCK_SIZE]; for (index, page) in pt.chunks(PAGE_SIZE).enumerate() { if page[..aes::BLOCK_SIZE] == blank { @@ -507,7 +508,7 @@ impl PddbOs { None } fn pt_as_slice(&self) -> &[u8] { - &self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::()] + unsafe { &self.pddb_mr.as_slice()[self.pt_phys_base.as_usize()..self.pt_phys_base.as_usize() + size_of::()] } } /// scans the page tables and returns all entries for a given basis @@ -639,7 +640,7 @@ impl PddbOs { /// maps a StaticCryptoData structure into the key area of the PDDB. fn static_crypto_data_get(&self) -> &StaticCryptoData { - let scd_ptr = self.pddb_mr.as_slice::()[self.key_phys_base.as_usize()..self.key_phys_base.as_usize() + PAGE_SIZE].as_ptr() as *const StaticCryptoData; + let scd_ptr = unsafe { self.pddb_mr.as_slice::()[self.key_phys_base.as_usize()..self.key_phys_base.as_usize() + PAGE_SIZE].as_ptr() as *const StaticCryptoData }; let scd: &StaticCryptoData = unsafe{scd_ptr.as_ref().unwrap()}; scd } @@ -781,7 +782,7 @@ impl PddbOs { } fn mbbb_as_slice(&self) -> &[u8] { - &self.pddb_mr.as_slice()[self.mbbb_phys_base.as_usize()..self.mbbb_phys_base.as_usize() + MBBB_PAGES * PAGE_SIZE] + unsafe { &self.pddb_mr.as_slice()[self.mbbb_phys_base.as_usize()..self.mbbb_phys_base.as_usize() + MBBB_PAGES * PAGE_SIZE] } } fn mbbb_retrieve(&self) -> Option<&[u8]> { // Invariant: MBBB pages should be blank, unless a page is stashed there. So, just check the first @@ -880,7 +881,7 @@ impl PddbOs { // We could "paper over" this by re-reading the data, but really, this problem should be solved by the d-cache // flush in the SPINOR primitive. let page_start = dest_page_start as usize * PAGE_SIZE; - let fscb_slice = &self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE]; + let fscb_slice = &unsafe { self.pddb_mr.as_slice() }[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE]; let mut fscb_buf = [0; FASTSPACE_PAGES * PAGE_SIZE - size_of::()]; // copy the encrypted data to the decryption buffer fscb_buf.copy_from_slice(&fscb_slice[page_start + size_of::() .. page_start + FASTSPACE_PAGES * PAGE_SIZE]); @@ -1095,7 +1096,7 @@ impl PddbOs { } fn fscb_deref(&self) -> &[u8] { - &self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE] + unsafe { &self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE] } } /// Reads the data structures in the FSCB, if any, and stores the results in the fspace_cache HashSet. /// Note the following convention on the fscb: if the first 128 bits of a page are all 1's, then that sector @@ -1122,7 +1123,7 @@ impl PddbOs { self.fspace_log_len = 0; // let fscb_slice = self.fscb_deref(); // can't use this line because it causse self to be immutably borrowed, so we write out the equivalent below. - let fscb_slice = &self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE]; + let fscb_slice = unsafe { &self.pddb_mr.as_slice()[self.fscb_phys_base.as_usize()..self.fscb_phys_base.as_usize() + FSCB_PAGES * PAGE_SIZE] }; // 1. scan through the entire space, and look for the FastSpace record. It can be identified by the // first 16 (aes::BLOCK_SIZE) bytes not being all 1's. @@ -1517,9 +1518,9 @@ impl PddbOs { /// We don't clip it off because it would require re-allocating a vector, and it's cheaper (although less elegant) to later /// just index past it. pub(crate) fn data_decrypt_page(&self, cipher: &Aes256GcmSiv, aad: &[u8], page: &PhysPage) -> Option> { - let ct_slice = &self.pddb_mr.as_slice()[ + let ct_slice = unsafe { &self.pddb_mr.as_slice()[ self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE .. - self.data_phys_base.as_usize() + (page.page_number() as usize + 1) * PAGE_SIZE]; + self.data_phys_base.as_usize() + (page.page_number() as usize + 1) * PAGE_SIZE] }; let nonce = &ct_slice[..size_of::()]; let ct = &ct_slice[size_of::()..]; match cipher.decrypt( @@ -1557,9 +1558,9 @@ impl PddbOs { const KCOM_NONCE_LEN: usize = 32; const KCOM_LEN: usize = 32; const MAC_LEN: usize = 16; - let ct_slice = &self.pddb_mr.as_slice()[ + let ct_slice = unsafe { &self.pddb_mr.as_slice()[ self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE .. - self.data_phys_base.as_usize() + (page.page_number() as usize + 1) * PAGE_SIZE]; + self.data_phys_base.as_usize() + (page.page_number() as usize + 1) * PAGE_SIZE] }; log::debug!("commit data at 0x{:x}", self.data_phys_base.as_usize() + page.page_number() as usize * PAGE_SIZE); let nonce = &ct_slice[..size_of::()]; let ct_total = &ct_slice[size_of::()..]; @@ -1838,7 +1839,7 @@ impl PddbOs { // do a blank check first to see if the sector really needs erasing let mut blank = true; let slice_start = (offset - xous::PDDB_LOC) as usize / size_of::(); - for word in self.pddb_mr.as_slice::()[slice_start..slice_start + SPINOR_BULK_ERASE_SIZE as usize / size_of::()].iter() { + for word in unsafe { self.pddb_mr.as_slice::()[slice_start..slice_start + SPINOR_BULK_ERASE_SIZE as usize / size_of::()].iter() } { if *word != 0xFFFF_FFFF { blank = false; break; @@ -2000,7 +2001,7 @@ impl PddbOs { // session key, previous data should be undecipherable. You shouldn't do this for a production erase // but this is good for speeding up testing. let mut is_blank = true; - let block: &[u8] = &self.pddb_mr.as_slice()[offset + aes::BLOCK_SIZE * 3..offset + aes::BLOCK_SIZE * 4]; + let block: &[u8] = unsafe { &self.pddb_mr.as_slice()[offset + aes::BLOCK_SIZE * 3..offset + aes::BLOCK_SIZE * 4] }; for (&a, &b) in block.iter().zip(blank.iter()) { if a != b { is_blank = false; @@ -2022,7 +2023,7 @@ impl PddbOs { } } self.spinor.patch( - self.pddb_mr.as_slice(), + unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, &temp, offset as u32 @@ -2184,7 +2185,7 @@ impl PddbOs { if let Some(mbbb) = self.mbbb_retrieve() { if let Some(erased_offset) = self.pt_find_erased_slot() { self.spinor.patch( - self.pddb_mr.as_slice(), + unsafe { self.pddb_mr.as_slice() }, xous::PDDB_LOC, &mbbb, self.pt_phys_base.as_u32() + erased_offset, @@ -2255,7 +2256,7 @@ impl PddbOs { // at the base of the `pddb_mr`. let pddb_data_len = PDDB_A_LEN - self.data_phys_base.as_usize(); let pddb_data_pages = pddb_data_len / PAGE_SIZE; - let pagetable: &[u8] = &self.pddb_mr.as_slice()[..pddb_data_pages * size_of::()]; + let pagetable: &[u8] = unsafe { &self.pddb_mr.as_slice()[..pddb_data_pages * size_of::()] }; log::info!("Derived page table of len 0x{:x}", pagetable.len()); let entries_per_page = PAGE_SIZE / size_of::(); modals.start_progress(t!("pddb.rekey.running", locales::LANG), 0, (pddb_data_pages * size_of::()) as u32, 0).ok(); @@ -2633,7 +2634,7 @@ impl PddbOs { pub(crate) fn checksums(&self, modals: Option::<&Modals>) -> root_keys::api::Checksums { let mut checksums = root_keys::api::Checksums::default(); - let pddb = self.pddb_mr.as_slice(); + let pddb = unsafe { self.pddb_mr.as_slice() }; if let Some(m) = modals { m.start_progress( t!("pddb.checksums", locales::LANG), diff --git a/services/pddb/src/lib.rs b/services/pddb/src/lib.rs index a2b1838c0..84d2e5d22 100644 --- a/services/pddb/src/lib.rs +++ b/services/pddb/src/lib.rs @@ -997,7 +997,8 @@ impl Pddb { let mut serializer = WriteSerializer::new(AlignedVec::new()); let pos = serializer.serialize_value(&request).unwrap(); let buf = serializer.into_inner(); - msg_mem.as_slice_mut()[..buf.len()].copy_from_slice(buf.as_slice()); + // Safety: `u8` contains no undefined values + unsafe { msg_mem.as_slice_mut()[..buf.len()].copy_from_slice(buf.as_slice()) }; // initiate the request: assemble a MemoryMessage let msg = xous::MemoryMessage { id: Opcode::DictBulkRead.to_usize().unwrap(), @@ -1016,8 +1017,9 @@ impl Pddb { // unpack the return code. The result is not a single rkyv struct, it's hand-packed binary data. Unpack it. let mut index = 0; let mut header = BulkReadHeader::default(); + // Safety: `u8` contains no undefined values header.deref_mut().copy_from_slice( - &msg_mem.as_slice()[index..index + size_of::()] + unsafe { &msg_mem.as_slice()[index..index + size_of::()] } ); index += size_of::(); match FromPrimitive::from_u32(header.code).unwrap_or(PddbBulkReadCode::InternalError) { @@ -1042,9 +1044,11 @@ impl Pddb { // quit if we don't have enough space to decode at least another two indices break; } - let size = u32::from_le_bytes(msg_mem.as_slice()[index..index + size_of::()].try_into().unwrap()); + // Safety: `u32` contains no undefined values + let size = unsafe { u32::from_le_bytes(msg_mem.as_slice()[index..index + size_of::()].try_into().unwrap()) }; index += size_of::(); - let pos = u32::from_le_bytes(msg_mem.as_slice()[index..index + size_of::()].try_into().unwrap()); + // Safety: `u32` contains no undefined values + let pos = unsafe { u32::from_le_bytes(msg_mem.as_slice()[index..index + size_of::()].try_into().unwrap()) }; index += size_of::(); log::trace!("unpacking message at {}({})", size, pos); if size != 0 && pos != 0 { diff --git a/services/pddb/src/libstd/mod.rs b/services/pddb/src/libstd/mod.rs index 39629f14a..b12e95bb3 100644 --- a/services/pddb/src/libstd/mod.rs +++ b/services/pddb/src/libstd/mod.rs @@ -44,7 +44,8 @@ pub(crate) fn stat_path( basis_cache: &mut BasisCache, ) -> Result<(), crate::PddbRetcode> { // Convert the memory to a Senres buffer - let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) + // Safety: the memory message must be aligned, and we test for validity here + let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) } .or(Err(crate::PddbRetcode::InternalError))?; let reader = backing @@ -148,7 +149,8 @@ pub(crate) fn list_path( basis_cache: &mut BasisCache, ) -> Result<(), crate::PddbRetcode> { // Convert the memory to a Senres buffer - let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) + // Safety: the memory message must be aligned, and we test for validity here + let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) } .or(Err(crate::PddbRetcode::InternalError))?; let reader = backing @@ -242,7 +244,8 @@ pub(crate) fn list_basis( let basis_list = basis_cache.basis_list(); // Convert the memory to a Senres buffer - let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) + // Safety: the memory message must be aligned, and we test for validity here + let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) } .or(Err(crate::PddbRetcode::InternalError))?; { @@ -273,7 +276,8 @@ pub(crate) fn open_key( fds: &mut Vec>, ) -> Result<(), crate::PddbRetcode> { // Convert the memory to a Senres buffer - let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) + // Safety: the memory message must be aligned, and we test for validity here + let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) } .or(Err(crate::PddbRetcode::InternalError))?; let create_file: bool; @@ -549,7 +553,8 @@ pub(crate) fn delete_key( all_fds: &mut std::collections::HashMap, Vec>>, ) -> Result<(), crate::PddbRetcode> { // Convert the memory to a Senres buffer - let backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) + // Safety: the memory message must be aligned, and we test for validity here + let backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) } .or(Err(crate::PddbRetcode::InternalError))?; let reader = backing @@ -618,12 +623,13 @@ pub(crate) fn write_key( file.key ); let length_to_write = mem.valid.map(|v| v.get()).unwrap_or_default(); + // Safety: all `u8` values are valid if basis_cache .key_update( pddb_os, &file.dict, &file.key, - &mem.buf.as_slice_mut()[0..length_to_write], + unsafe { &mem.buf.as_slice_mut()[0..length_to_write] }, // &mut pbuf.data[..pbuf.len as usize], Some(file.offset as usize), file.alloc_hint, @@ -712,12 +718,13 @@ pub(crate) fn read_key( file.basis.as_ref().unwrap_or(basis), file.key ); + // Safety: all u8 values are valid if let Ok(readlen) = basis_cache .key_read( pddb_os, &file.dict, &file.key, - &mut mem.buf.as_slice_mut()[0..mem.valid.map(|v| v.get()).unwrap_or_default()], + unsafe { &mut mem.buf.as_slice_mut()[0..mem.valid.map(|v| v.get()).unwrap_or_default()] }, Some(file.offset as usize), // this is a bit inefficient because if a specific basis is specified *and* the key does not exist, // it'll retry the same basis for a number of times equal to the number of bases open. @@ -756,7 +763,8 @@ pub(crate) fn list_dict( pddb_os: &mut PddbOs, basis_cache: &mut BasisCache, ) -> Result<(), crate::PddbRetcode> { - let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) + // Safety: the memory message must be aligned, and we test for validity here + let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) } .or(Err(crate::PddbRetcode::InternalError))?; let bname; { @@ -786,7 +794,8 @@ pub(crate) fn list_key( pddb_os: &mut PddbOs, basis_cache: &mut BasisCache, ) -> Result<(), crate::PddbRetcode> { - let mut backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) + // Safety: the memory message must be aligned, and we test for validity here + let mut backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) } .or(Err(crate::PddbRetcode::InternalError))?; let bname; let key; @@ -832,7 +841,8 @@ pub(crate) fn delete_dict( pddb_os: &mut PddbOs, basis_cache: &mut BasisCache, ) -> Result<(), crate::PddbRetcode> { - let backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) + // Safety: the memory message must be aligned, and we test for validity here + let backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) } .or(Err(crate::PddbRetcode::InternalError))?; let reader = backing .reader(*b"RmDQ") @@ -876,7 +886,8 @@ pub(crate) fn create_dict( pddb_os: &mut PddbOs, basis_cache: &mut BasisCache, ) -> Result<(), crate::PddbRetcode> { - let backing = senres::Message::from_mut_slice(mem.buf.as_slice_mut()) + // Safety: the memory message must be aligned, and we test for validity here + let backing = unsafe { senres::Message::from_mut_slice(mem.buf.as_slice_mut()) } .or(Err(crate::PddbRetcode::InternalError))?; let reader = backing .reader(*b"NuDQ") diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index 26e0c3606..bd5af8e51 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -812,7 +812,8 @@ fn wrapped_main() -> ! { if let Some(mem) = msg.body.memory_message_mut() { mem.offset = None; if let Some(name) = basis_cache.basis_latest() { - for (src, dest) in name.as_bytes().iter().zip(mem.buf.as_slice_mut().iter_mut()) { + // Safety: `u8` contains no undefined values + for (src, dest) in unsafe { name.as_bytes().iter().zip(mem.buf.as_slice_mut().iter_mut()) } { *dest = *src; } mem.offset = xous::MemorySize::new(name.len().min(mem.buf.len())); diff --git a/services/root-keys/src/implementation.rs b/services/root-keys/src/implementation.rs index ca9c99a1d..c20fca790 100644 --- a/services/root-keys/src/implementation.rs +++ b/services/root-keys/src/implementation.rs @@ -227,10 +227,10 @@ impl<'a> RootKeys { xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map sensitive data page"); // make sure the caches start out as zeros - for w in pass_cache.as_slice_mut::().iter_mut() { + for w in unsafe { pass_cache.as_slice_mut::().iter_mut() } { *w = 0; } - for w in sensitive_data.as_slice_mut::().iter_mut() { + for w in unsafe { sensitive_data.as_slice_mut::().iter_mut() } { *w = 0; } @@ -282,19 +282,19 @@ impl<'a> RootKeys { keys } pub fn gateware(&self) -> &[u8] { - self.gateware_mr.as_slice::() + unsafe { self.gateware_mr.as_slice::() } } pub fn gateware_base(&self) -> u32 { self.gateware_base } pub fn staging(&self) -> &[u8] { - self.staging_mr.as_slice::() + unsafe { self.staging_mr.as_slice::() } } pub fn staging_base(&self) -> u32 { self.staging_base } pub fn loader_code(&self) -> &[u8] { - self.loader_code_mr.as_slice::() + unsafe { self.loader_code_mr.as_slice::() } } pub fn loader_base(&self) -> u32 { self.loader_code_base } pub fn kernel(&self) -> &[u8] { - self.kernel_mr.as_slice::() + unsafe { self.kernel_mr.as_slice::() } } pub fn kernel_base(&self) -> u32 { self.kernel_base } @@ -634,13 +634,13 @@ impl<'a> RootKeys { core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); } pub fn purge_sensitive_data(&mut self) { - for d in self.sensitive_data.borrow_mut().as_slice_mut::().iter_mut() { + for d in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::().iter_mut() } { *d = 0; } core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); } fn populate_sensitive_data(&mut self) { - for (addr, d) in self.sensitive_data.borrow_mut().as_slice_mut::().iter_mut().enumerate() { + for (addr, d) in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::().iter_mut().enumerate() } { if addr > 255 { break; } @@ -664,13 +664,13 @@ impl<'a> RootKeys { // now encrypt the key, and store it into the sensitive_data for access later on by the patching routine if self.is_initialized() { for (dst, (key, pw)) in - self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize .. KeyRomLocs::FPGA_KEY as usize + 8].iter_mut().zip( + unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize .. KeyRomLocs::FPGA_KEY as usize + 8].iter_mut() }.zip( pcache.fpga_key.chunks(4).into_iter().zip(pcache.hashed_update_pw.chunks(4).into_iter())) { *dst = u32::from_be_bytes(key[0..4].try_into().unwrap()) ^ u32::from_be_bytes(pw[0..4].try_into().unwrap()); } } else { for (dst, key) in - self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize .. KeyRomLocs::FPGA_KEY as usize + 8].iter_mut().zip( + unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize .. KeyRomLocs::FPGA_KEY as usize + 8].iter_mut() }.zip( pcache.fpga_key.chunks(4).into_iter()) { *dst = u32::from_be_bytes(key[0..4].try_into().unwrap()); } @@ -830,7 +830,7 @@ impl<'a> RootKeys { fn read_staged_key_256(&mut self, index: u8) -> [u8; 32] { let mut key: [u8; 32] = [0; 32]; for (addr, word) in key.chunks_mut(4).into_iter().enumerate() { - let keyword = self.sensitive_data.borrow().as_slice::()[index as usize + addr]; + let keyword = unsafe { self.sensitive_data.borrow().as_slice::()[index as usize + addr] }; for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) { *dst = byte; } @@ -847,7 +847,7 @@ impl<'a> RootKeys { // we're not initialized, use the salt that should already be in the staging area let mut key: [u8; 16] = [0; 16]; for (word, &keyword) in key.chunks_mut(4).into_iter() - .zip(self.sensitive_data.borrow_mut().as_slice::() // get the sensitive_data as a slice &mut[u32] + .zip(unsafe { self.sensitive_data.borrow_mut().as_slice::() } // get the sensitive_data as a slice &mut[u32] [KeyRomLocs::PEPPER as usize..KeyRomLocs::PEPPER as usize + 128/(size_of::()*8)].iter()) { for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) { *dst = byte; @@ -904,11 +904,11 @@ impl<'a> RootKeys { // make a copy of the KEYROM to hold the new mods, in the sensitive data area for addr in 0..256 { self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, addr); - self.sensitive_data.borrow_mut().as_slice_mut::()[addr as usize] = self.keyrom.rf(utra::keyrom::DATA_DATA); + unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[addr as usize] = self.keyrom.rf(utra::keyrom::DATA_DATA) }; } // provision the pepper - for keyword in self.sensitive_data.borrow_mut().as_slice_mut::() + for keyword in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::() } [KeyRomLocs::PEPPER as usize..KeyRomLocs::PEPPER as usize + 128/(size_of::()*8)].iter_mut() { *keyword = self.trng.get_u32().expect("couldn't get random number"); } @@ -919,8 +919,8 @@ impl<'a> RootKeys { self.susres.set_suspendable(false).expect("couldn't block suspend/resume"); // populate the staging area, in particular we are interested in the "pepper" so passwords work correctly. - self.sensitive_data.borrow_mut().as_slice_mut::()[..256] - .copy_from_slice(&rom.0); + unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[..256] + .copy_from_slice(&rom.0) }; let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; // copy the plaintext FPGA key to the pcache @@ -928,8 +928,8 @@ impl<'a> RootKeys { pcache.fpga_key_valid = 1; // stage the plaintext FPGA key into the keyrom area for encryption by the key_init routine. - self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 32] - .copy_from_slice(&key.0); + unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 32] + .copy_from_slice(&key.0) }; self.restore_running = true; } @@ -1011,7 +1011,7 @@ impl<'a> RootKeys { // get access to the pcache and generate a keypair let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; // initialize the global rollback constant to 0 - self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::GLOBAL_ROLLBACK as usize] = 0; + unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::GLOBAL_ROLLBACK as usize] = 0 }; let mut root_sk = [0u8; ed25519_dalek::SECRET_KEY_LENGTH]; self.trng.fill_bytes(&mut root_sk); #[cfg(feature = "hazardous-debug")] @@ -1067,7 +1067,7 @@ impl<'a> RootKeys { pcache.fpga_key_valid = 1; // now encrypt it in the staging area - for (word, hashed_pass) in self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::()*8)].iter_mut() + for (word, hashed_pass) in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::()*8)].iter_mut() } .zip(pcache.hashed_update_pw.chunks(4).into_iter()) { *word = *word ^ u32::from_be_bytes(hashed_pass.try_into().unwrap()); } @@ -1088,7 +1088,7 @@ impl<'a> RootKeys { // pub key is easy, no need to encrypt let public_key: [u8; ed25519_dalek::PUBLIC_KEY_LENGTH] = keypair.public.to_bytes(); for (src, dst) in public_key.chunks(4).into_iter() - .zip(self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::SELFSIGN_PUBKEY as usize..KeyRomLocs::SELFSIGN_PUBKEY as usize + 256/(size_of::()*8)].iter_mut()) { + .zip(unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::SELFSIGN_PUBKEY as usize..KeyRomLocs::SELFSIGN_PUBKEY as usize + 256/(size_of::()*8)].iter_mut() }) { *dst = u32::from_be_bytes(src.try_into().unwrap()) } log::debug!("public key as computed: {:x?}", public_key); @@ -1110,7 +1110,7 @@ impl<'a> RootKeys { // store the private key to the keyrom staging area for (src, dst) in private_key_enc.chunks(4).into_iter() - .zip(self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::SELFSIGN_PRIVKEY as usize..KeyRomLocs::SELFSIGN_PRIVKEY as usize + 256/(size_of::()*8)].iter_mut()) { + .zip(unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::SELFSIGN_PRIVKEY as usize..KeyRomLocs::SELFSIGN_PRIVKEY as usize + 256/(size_of::()*8)].iter_mut() }) { *dst = u32::from_be_bytes(src.try_into().unwrap()) } #[cfg(feature = "hazardous-debug")] @@ -1135,7 +1135,7 @@ impl<'a> RootKeys { // store the boot key to the keyrom staging area for (src, dst) in boot_key_enc.chunks(4).into_iter() - .zip(self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::USER_KEY as usize..KeyRomLocs::USER_KEY as usize + 256/(size_of::()*8)].iter_mut()) { + .zip(unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::USER_KEY as usize..KeyRomLocs::USER_KEY as usize + 256/(size_of::()*8)].iter_mut() }) { *dst = u32::from_be_bytes(src.try_into().unwrap()) } @@ -1152,7 +1152,7 @@ impl<'a> RootKeys { log::debug!("loader len: {} bytes", loader_len); // set the "init" bit in the staging area - self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::CONFIG as usize] |= keyrom_config::INITIALIZED.ms(1); + unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::CONFIG as usize] |= keyrom_config::INITIALIZED.ms(1) }; #[cfg(feature = "hazardous-debug")] { @@ -1354,7 +1354,7 @@ impl<'a> RootKeys { old_key.copy_from_slice(&pcache.fpga_key); // now encrypt the FPGA key for the Keyrom in-place to the provided password - for (word, hashed_pass) in self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::()*8)].iter_mut() + for (word, hashed_pass) in unsafe { self.sensitive_data.borrow_mut().as_slice_mut::()[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::()*8)].iter_mut() } .zip(pcache.hashed_update_pw.chunks(4).into_iter()) { *word = *word ^ u32::from_be_bytes(hashed_pass.try_into().unwrap()); } @@ -2030,7 +2030,7 @@ impl<'a> RootKeys { // wrap the patch call with a range check, because the patch lookup search is pretty expensive if self.patch_in_range(src_oracle, from, from + spinor::SPINOR_ERASE_SIZE as u32) { - dummy_consume ^= self.patch_sector(src_oracle, from, &mut pt_sector, &self.sensitive_data.borrow_mut().as_slice_mut::()[0..256]); + dummy_consume ^= self.patch_sector(src_oracle, from, &mut pt_sector, unsafe { &self.sensitive_data.borrow_mut().as_slice_mut::()[0..256] }); } let hash_len = if bytes_hashed + decrypt_len < hash_stop { @@ -2947,4 +2947,4 @@ impl<'a> RootKeys { xous::KERNEL_BACKUP_OFFSET ).expect("couldn't erase backup region"); } -} \ No newline at end of file +} diff --git a/services/shellchat/src/cmds/test.rs b/services/shellchat/src/cmds/test.rs index 7f00cf7a2..7f20fb693 100644 --- a/services/shellchat/src/cmds/test.rs +++ b/services/shellchat/src/cmds/test.rs @@ -403,7 +403,7 @@ impl<'a> ShellCmdApi<'a> for Test { ).expect("couldn't allocate record buffer")); } if let Some(recbuf) = self.recbuf { - let recslice = recbuf.as_slice::(); + let recslice = unsafe { recbuf.as_slice::() }; const BUFLEN: usize = 512; // serialize and send audio as b64 encoded data for (i, sample) in recslice[recslice.len()-4096 * size_of::()..].chunks_exact(BUFLEN).enumerate() { @@ -822,7 +822,7 @@ impl<'a> ShellCmdApi<'a> for Test { ).expect("couldn't allocate record buffer")); } if let Some(mut recbuf) = self.recbuf { - let rec_samples = recbuf.as_slice_mut::(); + let rec_samples = unsafe { recbuf.as_slice_mut::() }; let rec_len = rec_samples.len(); loop { if let Some(frame) = frames.dq_frame() { diff --git a/services/status/src/ecup.rs b/services/status/src/ecup.rs index ea9324c18..6282bb11a 100644 --- a/services/status/src/ecup.rs +++ b/services/status/src/ecup.rs @@ -80,7 +80,7 @@ pub(crate) fn ecupdate_thread(sid: xous::SID) { xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map EC firmware package memory range"); #[cfg(not(target_os = "xous"))] - for d in ec_package.as_slice_mut::().iter_mut() { *d = 0xFF } // simulate blank flash + for d in unsafe { ec_package.as_slice_mut::().iter_mut() } { *d = 0xFF } // simulate blank flash #[cfg(not(target_os = "xous"))] let mut wf_package = xous::syscall::map_memory( None, @@ -89,7 +89,7 @@ pub(crate) fn ecupdate_thread(sid: xous::SID) { xous::MemoryFlags::R | xous::MemoryFlags::W, ).expect("couldn't map EC wf200 package memory range"); #[cfg(not(target_os = "xous"))] - for d in wf_package.as_slice_mut::().iter_mut() { *d = 0xFF } + for d in unsafe { wf_package.as_slice_mut::().iter_mut() } { *d = 0xFF } loop { let msg = xous::receive_message(sid).unwrap(); @@ -578,4 +578,4 @@ fn is_ec_rev_sane(ec_reported_rev: &SemVer) -> bool { true } } -} \ No newline at end of file +} diff --git a/xous-rs/src/arch/hosted/mod.rs b/xous-rs/src/arch/hosted/mod.rs index 48790449b..ec20370ef 100644 --- a/xous-rs/src/arch/hosted/mod.rs +++ b/xous-rs/src/arch/hosted/mod.rs @@ -246,7 +246,7 @@ fn read_next_syscall_result( memory_message.buf, ) .expect("couldn't allocate range"); - if let Err(e) = stream.read_exact(memory_message.buf.as_slice_mut()) { + if let Err(e) = stream.read_exact(unsafe { memory_message.buf.as_slice_mut() }) { eprintln!("Server shut down: {}", e); std::process::exit(0); } diff --git a/xous-rs/src/arch/riscv/process.rs b/xous-rs/src/arch/riscv/process.rs index 2d84398fe..4230c19ee 100644 --- a/xous-rs/src/arch/riscv/process.rs +++ b/xous-rs/src/arch/riscv/process.rs @@ -151,7 +151,7 @@ pub fn create_process_pre(args: &ProcessArgs) -> core::result::Result core::result::Result { if src > u8::MAX as _ { return Err(Error::InvalidPID); @@ -276,75 +273,6 @@ pub struct Context { pid: PID, } -impl MemoryRange { - /// # Safety - /// - /// This allows for creating a `MemoryRange` from any arbitrary pointer, - /// so it is imperitive that this only be used to point to valid, page-aligned - /// ranges. - pub unsafe fn new(addr: usize, size: usize) -> core::result::Result { - Ok(MemoryRange { - addr: MemoryAddress::new(addr).ok_or(Error::BadAddress)?, - size: MemorySize::new(size).ok_or(Error::BadAddress)?, - }) - } - - #[deprecated(since = "0.8.4", note = "Please use `new(addr, size)` instead")] - pub fn from_parts(addr: MemoryAddress, size: MemorySize) -> MemoryRange { - MemoryRange { addr, size } - } - - pub fn len(&self) -> usize { - self.size.get() - } - - pub fn is_empty(&self) -> bool { - self.size.get() > 0 - } - - pub fn as_ptr(&self) -> *const u8 { - self.addr.get() as *const u8 - } - - pub fn as_mut_ptr(&self) -> *mut u8 { - self.addr.get() as *mut u8 - } - - /// Return this memory as a slice of values. The resulting slice - /// will cover the maximum number of elements given the size of `T`. - /// For example, if the allocation is 4096 bytes, then the resulting - /// `&[u8]` would have 4096 elements, `&[u16]` would have 2048, and - /// `&[u32]` would have 1024. Values are rounded down. - pub fn as_slice(&self) -> &[T] { - // This is safe because the pointer and length are guaranteed to - // be valid, as long as the user hasn't already called `as_ptr()` - // and done something unsound with the resulting pointer. - unsafe { - core::slice::from_raw_parts( - self.as_ptr() as *const T, - self.len() / core::mem::size_of::(), - ) - } - } - - /// Return this memory as a slice of mutable values. The resulting slice - /// will cover the maximum number of elements given the size of `T`. - /// For example, if the allocation is 4096 bytes, then the resulting - /// `&[u8]` would have 4096 elements, `&[u16]` would have 2048, and - /// `&[u32]` would have 1024. Values are rounded down. - pub fn as_slice_mut(&mut self) -> &mut [T] { - // This is safe because the pointer and length are guaranteed to - // be valid, as long as the user hasn't already called `as_ptr()` - // and done something unsound with the resulting pointer. - unsafe { - core::slice::from_raw_parts_mut( - self.as_mut_ptr() as *mut T, - self.len() / core::mem::size_of::(), - ) - } - } -} - /// Which memory region the operation should affect. #[derive(Debug, Copy, Clone, PartialEq)] pub enum MemoryType { diff --git a/xous-rs/src/definitions/memoryrange.rs b/xous-rs/src/definitions/memoryrange.rs new file mode 100644 index 000000000..734c507d5 --- /dev/null +++ b/xous-rs/src/definitions/memoryrange.rs @@ -0,0 +1,83 @@ +use crate::definitions::{Error, MemoryAddress, MemorySize}; + +#[derive(Debug, PartialEq, Copy, Clone)] +pub struct MemoryRange { + pub(crate) addr: MemoryAddress, + pub(crate) size: MemorySize, +} + +impl MemoryRange { + /// # Safety + /// + /// This allows for creating a `MemoryRange` from any arbitrary pointer, + /// so it is imperitive that this only be used to point to valid, page-aligned + /// ranges. + pub unsafe fn new(addr: usize, size: usize) -> core::result::Result { + Ok(MemoryRange { + addr: MemoryAddress::new(addr).ok_or(Error::BadAddress)?, + size: MemorySize::new(size).ok_or(Error::BadAddress)?, + }) + } + + pub fn len(&self) -> usize { + self.size.get() + } + + pub fn is_empty(&self) -> bool { + self.size.get() > 0 + } + + pub fn as_ptr(&self) -> *const u8 { + self.addr.get() as *const u8 + } + + pub fn as_mut_ptr(&self) -> *mut u8 { + self.addr.get() as *mut u8 + } + + /// Return this memory as a slice of values. The resulting slice + /// will cover the maximum number of elements given the size of `T`. + /// For example, if the allocation is 4096 bytes, then the resulting + /// `&[u8]` would have 4096 elements, `&[u16]` would have 2048, and + /// `&[u32]` would have 1024. Values are rounded down. + /// + /// # Safety + /// + /// This is safe as long as the underlying memory is representable + /// on the target system. For example, you must ensure that `bool` + /// slices contain only `0` or `1`. + pub unsafe fn as_slice(&self) -> &[T] { + // This is safe because the pointer and length are guaranteed to + // be valid, as long as the user hasn't already called `as_ptr()` + // and done something unsound with the resulting pointer. + unsafe { + core::slice::from_raw_parts( + self.as_ptr() as *const T, + self.len() / core::mem::size_of::(), + ) + } + } + + /// Return this memory as a slice of mutable values. The resulting slice + /// will cover the maximum number of elements given the size of `T`. + /// For example, if the allocation is 4096 bytes, then the resulting + /// `&[u8]` would have 4096 elements, `&[u16]` would have 2048, and + /// `&[u32]` would have 1024. Values are rounded down. + /// + /// # Safety + /// + /// This is safe as long as the underlying memory is representable + /// on the target system. For example, you must ensure that `bool` + /// slices contain only `0` or `1`. + pub unsafe fn as_slice_mut(&mut self) -> &mut [T] { + // This is safe because the pointer and length are guaranteed to + // be valid, as long as the user hasn't already called `as_ptr()` + // and done something unsound with the resulting pointer. + unsafe { + core::slice::from_raw_parts_mut( + self.as_mut_ptr() as *mut T, + self.len() / core::mem::size_of::(), + ) + } + } +} diff --git a/xous-rs/src/lib.rs b/xous-rs/src/lib.rs index 7a5d6aeb7..c86a9dd51 100644 --- a/xous-rs/src/lib.rs +++ b/xous-rs/src/lib.rs @@ -18,4 +18,4 @@ pub use stringbuffer::*; pub use syscall::*; #[cfg(feature = "processes-as-threads")] -pub use crate::arch::ProcessArgsAsThread; \ No newline at end of file +pub use crate::arch::ProcessArgsAsThread;