apache / apache/nuttx

[BUG] Crash in setenv with Invalid Pointer

Open
#15,401 4 comments 0 reactions 0 assignees View on GitHub
Arch: risc-v Area: Kernel OS: Linux Type: Bug
Dominant language
C
Stars
4k
Forks
1.7k
Avg merge
1d 17h
Merged PRs (30d)
237

Description

### Description / Steps to reproduce the issue

When using the ```setenv``` function in NuttX, I encountered a potential issue where the function crashes if an invalid or inaccessible pointer is passed to the value parameter. Specifically:

When calling my_setenv(0x8001, 0x0, 0x9), the program runs without any issues. However, when calling my_setenv(0x7, 0x5, 0x8), the program crashes.

Use the following code:
```c
static long my_setenv(volatile long name_ptr, volatile long value_ptr, volatile long overwrite)
{
const char *name = (const char *)name_ptr;
const char *value = (const char *)value_ptr;
return (long)setenv(name, value, (int)overwrite);
}

int main(int argc, FAR char *argv[])
{
printf("CPU0: Beginning Idle Loop\n");
executor_check_ints();
my_setenv(0x8001, 0x0, 0x9); // Runs without error
my_setenv(0x7, 0x5, 0x8); // Crashes here
printf("CPU0: Finish\n");
}
```
Compile and run the program using:
```bash
cmake -B build_new4 -DBOARD_CONFIG=rv-virt:nsh64 -GNinja
cmake --build build_new4 -t clean && cmake --build build_new4
```
run using
``` bash
qemu-system-riscv64 -semihosting -M virt,aclint=on -cpu rv64 -smp 8 -bios none -kernel /root/HJ/nuttx/nuttx-nocov/build_new4/nuttx -nographic
```
Then the program keeps crashing.

Using GDB, I traced the issue to the following line in setenv:

```c
if (!value || !value[0])
```
When ```value=0x5```, the program attempts to dereference an inaccessible memory address, resulting in a crash. It seems the pointer is dereferenced without first checking whether it is valid or accessible.

To handle such cases more robustly, the function could validate the accessibility of the value pointer before dereferencing it. For example, using access_ok() might help ensure the pointer is valid.

### On which OS does this issue occur?

[OS: Linux]

### What is the version of your OS?

Debian GNU/Linux 12 (bookworm)

### NuttX Version

fc993539aa

### Issue Architecture

[Arch: risc-v]

### Issue Area

[Area: Kernel]

### Verification

- [X] I have verified before submitting the report.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.