Skip to content

Commit

Permalink
Add additional checks to prevent OOB panics in BLE advertisement parser
Browse files Browse the repository at this point in the history
  • Loading branch information
kpcyrd committed Nov 25, 2023
1 parent fbbf6b5 commit 4b66d6c
Showing 1 changed file with 18 additions and 12 deletions.
30 changes: 18 additions & 12 deletions src/client/ble_advertised_device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,30 +90,32 @@ impl BLEAdvertisedDevice {
let mut payload = payload;

loop {
if payload.is_empty() {
return;
}
let Some(length) = payload.get(0) else { return };
let length = *length as usize;

let length = payload[0] as usize;
if length != 0 {
let type_ = payload[1] as u32;
let data = &payload[2..(length + 1)];
let Some(type_) = payload.get(1) else { return };
let type_ = *type_ as u32;

let Some(data) = payload.get(2..(length + 1)) else { return };

match type_ {
esp_idf_sys::BLE_HS_ADV_TYPE_FLAGS => {
self.ad_flag = Some(data[0]);
let Some(ad_flag) = data.get(0) else { return };
self.ad_flag = Some(*ad_flag);
}
esp_idf_sys::BLE_HS_ADV_TYPE_INCOMP_NAME | esp_idf_sys::BLE_HS_ADV_TYPE_COMP_NAME => {
self.name = unsafe { String::from_utf8_unchecked(data.to_vec()) };
}
esp_idf_sys::BLE_HS_ADV_TYPE_TX_PWR_LVL => {
self.tx_power = Some(data[0]);
let Some(tx_power) = data.get(0) else { return };
self.tx_power = Some(*tx_power);
}

esp_idf_sys::BLE_HS_ADV_TYPE_INCOMP_UUIDS16
| esp_idf_sys::BLE_HS_ADV_TYPE_COMP_UUIDS16 => {
let mut data = data;
while !data.is_empty() {
while data.len() >= 2 {
let (uuid, data_) = data.split_at(2);
self.push_service_uuid(BleUuid::from_uuid16(u16::from_le_bytes(
uuid.try_into().unwrap(),
Expand All @@ -124,7 +126,7 @@ impl BLEAdvertisedDevice {
esp_idf_sys::BLE_HS_ADV_TYPE_INCOMP_UUIDS32
| esp_idf_sys::BLE_HS_ADV_TYPE_COMP_UUIDS32 => {
let mut data = data;
while !data.is_empty() {
while data.len() >= 4 {
let (uuid, data_) = data.split_at(4);
self.push_service_uuid(BleUuid::from_uuid32(u32::from_le_bytes(
uuid.try_into().unwrap(),
Expand All @@ -134,7 +136,9 @@ impl BLEAdvertisedDevice {
}
esp_idf_sys::BLE_HS_ADV_TYPE_INCOMP_UUIDS128
| esp_idf_sys::BLE_HS_ADV_TYPE_COMP_UUIDS128 => {
self.push_service_uuid(BleUuid::Uuid128(data.try_into().unwrap()));
if let Ok(data) = data.try_into() {
self.push_service_uuid(BleUuid::Uuid128(data));
}
}
esp_idf_sys::BLE_HS_ADV_TYPE_SVC_DATA_UUID16 => {
if length < 2 {
Expand Down Expand Up @@ -164,7 +168,9 @@ impl BLEAdvertisedDevice {
}
}
esp_idf_sys::BLE_HS_ADV_TYPE_APPEARANCE => {
self.appearance = Some(u16::from_le_bytes(data.try_into().unwrap()));
if let Ok(appearance) = data.try_into() {
self.appearance = Some(u16::from_le_bytes(appearance));
}
}
esp_idf_sys::BLE_HS_ADV_TYPE_MFG_DATA => {
self.manufacture_data = Some(data.to_vec());
Expand Down

0 comments on commit 4b66d6c

Please sign in to comment.