diff --git a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs index 32550ba82..0a10f3026 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs @@ -421,7 +421,7 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa ) }; - crate::println!("scratch page: {:x}, heap start: {:x}", SCRATCH_PAGE, HEAP_START); + // crate::println!("scratch page: {:x}, heap start: {:x}", SCRATCH_PAGE, HEAP_START); // setup heap alloc setup_alloc(); @@ -468,8 +468,8 @@ pub fn setup_timer(sysclk_freq: u32) { pub fn setup_alloc() { // Initialize the allocator with heap memory range - crate::println!("Setting up heap @ {:x}-{:x}", HEAP_START, HEAP_START + HEAP_LEN); - crate::println!("Stack @ {:x}-{:x}", HEAP_START + HEAP_LEN, RAM_BASE + RAM_SIZE); + // crate::println!("Setting up heap @ {:x}-{:x}", HEAP_START, HEAP_START + HEAP_LEN); + // crate::println!("Stack @ {:x}-{:x}", HEAP_START + HEAP_LEN, RAM_BASE + RAM_SIZE); unsafe { ALLOCATOR.lock().init(HEAP_START as *mut u8, HEAP_LEN); } @@ -503,8 +503,11 @@ pub fn delay(ms: usize) { mod panic_handler { use core::panic::PanicInfo; + + use crate::USB_CONNECTED; #[panic_handler] fn handle_panic(_arg: &PanicInfo) -> ! { + USB_CONNECTED.store(false, core::sync::atomic::Ordering::SeqCst); crate::println!("{}", _arg); loop {} } diff --git a/bao1x-boot/boot1/src/platform/bao1x/usb/driver.rs b/bao1x-boot/boot1/src/platform/bao1x/usb/driver.rs index ce15be7fc..ac11a0969 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/usb/driver.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/usb/driver.rs @@ -61,6 +61,7 @@ fn get_status_request(this: &mut CorigineUsb, request_type: u8, index: u16) { CRG_UDC_EP0_REQBUFSIZE, ) }; + udc_pointer_check(ep0_buf.as_ptr() as usize, ep0_buf.len()); let mut status_val: u32 = 0; let recipient = request_type & 0x1f; @@ -134,6 +135,8 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent { let residual_length = event_trb.dw2.trb_tran_len() as u16; // update the dequeue pointer // crate::println_d!("event_transfer {:x?}", event_trb); + udc_pointer_check(event_trb.dw0 as usize, size_of::() * 2); + // safety: checked that there's at least space for the increment of the pointer let deq_pt = unsafe { (event_trb.dw0 as *mut TransferTrbS).add(1).as_mut().expect("Couldn't deref ptr") }; if deq_pt.get_trb_type() == TrbType::Link { @@ -161,8 +164,10 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent { // crate::println_d!("EP{} xfer event, dir {}", ep_num, if dir { "OUT" } else { "IN" }); // xfer_complete if let Some(f) = this.udc_ep[pei as usize].completion_handler { + udc_pointer_check(event_trb.dw0 as usize, size_of::()); // so unsafe. so unsafe. We're counting on the hardware to hand us a raw pointer - // that isn't corrupted. + // that isn't corrupted. The check above assures that the pointer is at least within + // the designated range of memory for the UDC hardware controller let p_trb = unsafe { &*(event_trb.dw0 as *const TransferTrbS) }; #[cfg(feature = "verbose-debug")] crate::println_d!( @@ -280,6 +285,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent { CRG_UDC_EP0_REQBUFSIZE, ) }; + udc_pointer_check(ep0_buf.as_ptr() as usize, ep0_buf.len()); if this.get_device_state() != UsbDeviceState::Configured { ep0_buf[0] = 0; } else { @@ -301,6 +307,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent { CRG_UDC_EP0_REQBUFSIZE, ) }; + udc_pointer_check(ep0_buf.as_ptr() as usize, ep0_buf.len()); ep0_buf[0] = this.cur_interface_num; this.ep0_send(ep0_buf.as_ptr() as usize, 1, 0); } @@ -344,6 +351,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent { CRG_UDC_EP0_REQBUFSIZE, ) }; + udc_pointer_check(ep0_buf.as_ptr() as usize, ep0_buf.len()); ep0_buf[0] = 0; this.ep0_send(ep0_buf.as_ptr() as usize, 1, 0); } @@ -369,6 +377,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent { CRG_UDC_EP0_REQBUFSIZE, ) }; + udc_pointer_check(ep0_buf.as_ptr() as usize, ep0_buf.len()); // Fill with a dummy 115200 8N1 config ep0_buf[0..4].copy_from_slice(&115200u32.to_le_bytes()); // dwDTERate ep0_buf[4] = 0; // 1 stop bit diff --git a/bao1x-boot/boot1/src/platform/bao1x/usb/handlers.rs b/bao1x-boot/boot1/src/platform/bao1x/usb/handlers.rs index ddbcc413d..759c5ca17 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/usb/handlers.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/usb/handlers.rs @@ -3,6 +3,7 @@ use core::sync::atomic::Ordering; use bao1x_api::KERNEL_START; use bao1x_api::*; +use bao1x_hal::hardening::die; use bao1x_hal::iox::Iox; use bao1x_hal::sh1107::Oled128x128; use bao1x_hal::udma::*; @@ -22,6 +23,18 @@ pub(crate) const RAMDISK_ADDRESS: usize = crate::FREE_MEM_START; pub(crate) const RAMDISK_ACTUAL_LEN: usize = crate::FREE_MEM_LEN; pub(crate) const RAMDISK_LEN: usize = 128 * 1024 * 1024; // present as a 128MiB disk. Big enough for "any" update? pub(crate) const SECTOR_SIZE: u16 = 512; +pub(crate) const APP_BUF_LEN: usize = 4096 * 2; + +#[inline(always)] +/// This function checks that any raw pointers passed back from the hardware +/// are within the allocated ranges for the UDC block to use. +pub(crate) fn udc_pointer_check(base: usize, len: usize) { + assert!( + (base >= HW_IFRAM1_MEM && (base + len) <= HW_IFRAM1_MEM + APP_BUF_LEN) + || (base >= bao1x_hal::board::CRG_UDC_MEMBASE + && (base + len) <= (bao1x_hal::board::CRG_UDC_MEMBASE + CRG_IFRAM_PAGES * 4096)), + ); +} fn fill_sparse_data(dest: &mut [u8], offset: usize) { let dest_start = offset; @@ -105,6 +118,7 @@ pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, CRG_UDC_EP0_REQBUFSIZE, ) }; + udc_pointer_check(ep0_buf.as_ptr() as usize, ep0_buf.len()); match (value >> 8) as u8 { USB_DT_DEVICE => { @@ -185,6 +199,8 @@ pub fn usb_ep1_bulk_out_complete( _residual: u16, ) { let length = info & 0xFFFF; + udc_pointer_check(buf_addr, info as usize & 0xFFFF); + // safety: the buffer is checked to be in-range for the UDC handler let buf = unsafe { core::slice::from_raw_parts(buf_addr as *const u8, info as usize & 0xFFFF) }; let mut cbw = Cbw::default(); cbw.as_mut().copy_from_slice(&buf[..size_of::()]); @@ -216,7 +232,11 @@ pub fn usb_ep1_bulk_out_complete( let app_buf = conjure_app_buf(); let disk = conjure_disk(); // process the received data as if it were a uf2 sector + // This loop is perhaps the most dangerous loop in the bootloader: if these range checks + // on the addresses can be bypassed, then you potentially have an arbitrary-write primitive + // into RRAM via USB. for (i, chunk) in app_buf[..len].chunks(512).enumerate() { + bollard!(die, 4); let (new_block, uf2_data) = critical_section::with(|cs| { super::glue::SECTOR .borrow(cs) @@ -235,11 +255,15 @@ pub fn usb_ep1_bulk_out_complete( const START_RANGE: usize = bao1x_api::BOOT1_START; // program the flash if a valid u2f block was found if let Some(record) = uf2_data { + bollard!(die, 4); + // This range check prevents UF2 from being an arbitrary-write primitive to e.g. RAM + // or sensitive bootloader code. if matches!(record.address() as usize, START_RANGE..=STORAGE_END_ADDR) && record.family() == bao1x_api::BAOCHIP_1X_UF2_FAMILY { let mut rram = bao1x_hal::rram::Reram::new(); let offset = record.address() as usize - utralib::HW_RERAM_MEM; + bollard!(die, 4); match rram.write_slice(offset, record.data()) { Err(e) => crate::print_d!("Write error {:?} @ {:x}", e, offset), Ok(_) => (), @@ -407,6 +431,8 @@ pub fn usb_ep1_bulk_in_complete( if let Some((offset, len)) = this.remaining_rd.take() { let app_buf = conjure_app_buf(); let disk = conjure_disk(); + // this is protected by the `disk` slice having a defined length. `setup_big_read` copies data + // from `disk` to `app_buf` using only safe operations, and "fakes" the data if it's out of range. this.setup_big_read(app_buf, disk, offset, len, Some(fill_sparse_data)); this.ms_state = UmsState::DataPhase; } else { @@ -438,6 +464,8 @@ pub fn usb_ep3_bulk_out_complete( } // Slice of received data + udc_pointer_check(buf_addr, actual); + // safety: buffer is checked to be within the UDC memory range let buf = unsafe { core::slice::from_raw_parts(buf_addr as *const u8, actual as usize) }; // For now: just print, or push into a ring buffer for your "virtual terminal" @@ -622,6 +650,7 @@ fn process_request_sense(this: &mut CorigineUsb, cbw: Cbw) { // crate::println_d!("UMS_STATE_STATUS_PHASE\r\n"); } else if cbw.flags & 0x80 != 0 { if cbw.data_transfer_length < 18 { + udc_pointer_check(EP1_IN_BUF, EP1_IN_BUF_LEN); let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) }; ep1_in[..18].fill(0); this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, cbw.data_transfer_length as usize, 0, 0); @@ -629,6 +658,7 @@ fn process_request_sense(this: &mut CorigineUsb, cbw: Cbw) { csw.residue = 0; csw.status = 0; } else if cbw.data_transfer_length >= 18 { + udc_pointer_check(EP1_IN_BUF, EP1_IN_BUF_LEN); let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) }; ep1_in[..18].fill(0); this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, 18, 0, 0); @@ -662,6 +692,7 @@ fn process_inquiry_command(this: &mut CorigineUsb, cbw: Cbw) { csw.send(this); } else if cbw.flags & 0x80 != 0 { if cbw.data_transfer_length < 36 { + udc_pointer_check(EP1_IN_BUF, EP1_IN_BUF_LEN); let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) }; ep1_in[..36].fill(0); this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, cbw.data_transfer_length as usize, 0, 0); @@ -669,6 +700,7 @@ fn process_inquiry_command(this: &mut CorigineUsb, cbw: Cbw) { csw.residue = 0; csw.status = 0; } else if cbw.data_transfer_length as usize >= size_of::() { + udc_pointer_check(EP1_IN_BUF, EP1_IN_BUF_LEN); let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) }; ep1_in[..size_of::()].copy_from_slice(inquiry_data.as_ref()); @@ -699,6 +731,7 @@ fn process_report_capacity(this: &mut CorigineUsb, cbw: Cbw) { capacity[4..].copy_from_slice(&rc_bl.to_be_bytes()); if cbw.flags & 0x80 != 0 { + udc_pointer_check(EP1_IN_BUF, EP1_IN_BUF_LEN); let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) }; ep1_in[..8].fill(0); ep1_in[..8].copy_from_slice(&capacity); @@ -719,6 +752,7 @@ fn process_read_capacity_16(this: &mut CorigineUsb, _cbw: Cbw) { let mut response = [0u8; 32]; response[..8].copy_from_slice(&rc_lba.to_be_bytes()); response[8..12].copy_from_slice(&rc_bl.to_be_bytes()); + udc_pointer_check(EP1_IN_BUF, EP1_IN_BUF_LEN); let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) }; ep1_in[..32].copy_from_slice(&response); this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, 32, 0, 0); @@ -932,11 +966,14 @@ fn process_write12_command(this: &mut CorigineUsb, cbw: Cbw) { // Place the application buf in IFRAM1 range - this removes any conflicts with the USB stack's IFRAM0 // allocations pub(crate) fn app_buf_addr() -> usize { HW_IFRAM1_MEM } -pub(crate) fn app_buf_len() -> usize { 4096 * 2 } +pub(crate) fn app_buf_len() -> usize { APP_BUF_LEN } pub(crate) fn conjure_app_buf() -> &'static mut [u8] { + udc_pointer_check(app_buf_addr(), app_buf_len()); unsafe { core::slice::from_raw_parts_mut(app_buf_addr() as *mut u8, app_buf_len()) } } pub(crate) fn conjure_disk() -> &'static mut [u8] { + // safety: these constants just have to be very carefully vetted. Definitely a risk that + // the ramdisk size could overrun e.g. the stack, etc. unsafe { core::slice::from_raw_parts_mut(RAMDISK_ADDRESS as *mut u8, RAMDISK_ACTUAL_LEN) } } diff --git a/bao1x-boot/boot1/src/platform/bao1x/usb/mod.rs b/bao1x-boot/boot1/src/platform/bao1x/usb/mod.rs index 8d693af16..6ef966571 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/usb/mod.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/usb/mod.rs @@ -201,6 +201,7 @@ impl DeviceDescriptor { impl AsRef<[u8]> for DeviceDescriptor { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const DeviceDescriptor as *const u8, @@ -241,6 +242,7 @@ impl QualifierDescriptor { } impl AsRef<[u8]> for QualifierDescriptor { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const QualifierDescriptor as *const u8, @@ -279,6 +281,7 @@ impl ConfigDescriptor { } impl AsRef<[u8]> for ConfigDescriptor { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const ConfigDescriptor as *const u8, @@ -352,6 +355,7 @@ impl InterfaceDescriptor { } impl AsRef<[u8]> for InterfaceDescriptor { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const InterfaceDescriptor as *const u8, @@ -451,6 +455,7 @@ impl EndpointDescriptor { impl AsRef<[u8]> for EndpointDescriptor { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const EndpointDescriptor as *const u8, @@ -471,6 +476,7 @@ struct CtrlRequest { } impl AsMut<[u8]> for CtrlRequest { fn as_mut(&mut self) -> &mut [u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts_mut( self as *const CtrlRequest as *mut u8, @@ -501,6 +507,7 @@ impl BosDescriptor { impl AsRef<[u8]> for BosDescriptor { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const BosDescriptor as *const u8, @@ -531,6 +538,7 @@ impl ExtCapDescriptor { impl AsRef<[u8]> for ExtCapDescriptor { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const ExtCapDescriptor as *const u8, @@ -562,6 +570,7 @@ struct Cbw { } impl AsMut<[u8]> for Cbw { fn as_mut(&mut self) -> &mut [u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts_mut(self as *mut Cbw as *mut u8, core::mem::size_of::()) as &mut [u8] @@ -570,6 +579,7 @@ impl AsMut<[u8]> for Cbw { } impl AsRef<[u8]> for Cbw { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts(self as *const Cbw as *const u8, core::mem::size_of::()) as &[u8] @@ -590,6 +600,7 @@ struct Csw { impl Csw { fn derive() -> Csw { let mut csw = Csw::default(); + udc_pointer_check(handlers::CSW_ADDR, size_of::()); csw.as_mut().copy_from_slice(unsafe { core::slice::from_raw_parts(handlers::CSW_ADDR as *mut u8, size_of::()) }); @@ -597,11 +608,13 @@ impl Csw { } fn update_hw(&self) { + udc_pointer_check(handlers::CSW_ADDR, size_of::()); let csw_buf = unsafe { core::slice::from_raw_parts_mut(CSW_ADDR as *mut u8, size_of::()) }; csw_buf.copy_from_slice(self.as_ref()); } fn send(&self, usb: &mut bao1x_hal::usb::driver::CorigineUsb) { + udc_pointer_check(handlers::CSW_ADDR, size_of::()); let csw_buf = unsafe { core::slice::from_raw_parts_mut(CSW_ADDR as *mut u8, size_of::()) }; csw_buf.copy_from_slice(self.as_ref()); usb.bulk_xfer(1, bao1x_hal::usb::driver::USB_SEND, CSW_ADDR, size_of::(), 0, 0); @@ -612,6 +625,7 @@ const BULK_CSW_SIG: u32 = 0x53425355; /* Spells out 'USBS' */ impl AsRef<[u8]> for Csw { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts(self as *const Csw as *const u8, core::mem::size_of::()) as &[u8] @@ -621,6 +635,7 @@ impl AsRef<[u8]> for Csw { impl AsMut<[u8]> for Csw { fn as_mut(&mut self) -> &mut [u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts_mut(self as *mut Csw as *mut u8, core::mem::size_of::()) as &mut [u8] @@ -644,6 +659,7 @@ struct InquiryResponse { } impl AsRef<[u8]> for InquiryResponse { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const InquiryResponse as *const u8, @@ -681,6 +697,7 @@ impl IadDescriptor { } impl AsRef<[u8]> for IadDescriptor { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const IadDescriptor as *const u8, @@ -710,6 +727,7 @@ impl CdcHeaderFuncDesc { } impl AsRef<[u8]> for CdcHeaderFuncDesc { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const CdcHeaderFuncDesc as *const u8, @@ -740,6 +758,7 @@ impl CdcCallMgmtFuncDesc { } impl AsRef<[u8]> for CdcCallMgmtFuncDesc { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const CdcCallMgmtFuncDesc as *const u8, @@ -768,6 +787,7 @@ impl CdcAcmFuncDesc { } impl AsRef<[u8]> for CdcAcmFuncDesc { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const CdcAcmFuncDesc as *const u8, @@ -798,6 +818,7 @@ impl CdcUnionFuncDesc { } impl AsRef<[u8]> for CdcUnionFuncDesc { fn as_ref(&self) -> &[u8] { + // all values are representable in this cast, since we're going to slice-u8 unsafe { core::slice::from_raw_parts( self as *const CdcUnionFuncDesc as *const u8,