bluekitchen / btstack

Dual-mode Bluetooth stack, with small memory footprint.
http://bluekitchen-gmbh.com
Other
1.74k stars 613 forks source link

Integer Overflow #546

Closed 0xfocu5 closed 1 year ago

0xfocu5 commented 1 year ago

Describe the bug

i got a Integer Overflow with this test file。

#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
typedef uint8_t   u8;   
typedef uint16_t  u16;  
typedef uint32_t  u32;  
typedef uint64_t  u64;
typedef unsigned int usize;
typedef int8_t  i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
typedef int isize;
typedef float f32;
typedef double f64;
int main() {
    i32 v0 = -2147483643; // nibble
    i8 v1 = char_for_nibble(v0); // $target
}
char char_for_nibble(int nibble){

    static const char * char_to_nibble = "0123456789ABCDEF";

    if (nibble < 16){
        return char_to_nibble[nibble];
    } else {
        return '?';
    }
}

static inline char char_for_high_nibble(int value){
    return char_for_nibble((value >> 4) & 0x0f);
}

static inline char char_for_low_nibble(int value){
    return char_for_nibble(value & 0x0f);
}

and i saw this source c file in btstack/src/btstack_util.c

char char_for_nibble(int nibble){

    static const char * char_to_nibble = "0123456789ABCDEF";

    if (nibble < 16){
        return char_to_nibble[nibble];
    } else {
        return '?';
    }
}

static inline char char_for_high_nibble(int value){
    return char_for_nibble((value >> 4) & 0x0f);
}

static inline char char_for_low_nibble(int value){
    return char_for_nibble(value & 0x0f);
}

it just check nibble less than 16 but nibble is a Integer and it can be a negative,so it will be stack overflow

Discover by 0xfocu5&Taolaw@vecentek

mringwal commented 1 year ago

Thanks for reporting this inconsistency. We've update the API to use uint8_t for the nibble parameter on the develop branch.

mringwal commented 1 year ago

This is an local API functions that returns an invalid result if called with an unexpected input. Calling it with an incorrect value should actually trigger an assert instead of returning a question mark.

Can you trigger this integer overflow from a remote device via Bluetooth?

0xfocu5 commented 1 year ago

This is an local API functions that returns an invalid result if called with an unexpected input. Calling it with an incorrect value should actually trigger an assert instead of returning a question mark.

Can you trigger this integer overflow from a remote device via Bluetooth?

"I have only tried it locally and haven't attempted it remotely yet."