# napi_get_value_string_X allow various kinds of memory corruption

Integer underflow in N-API string getters with bufsize=0 causes out-of-bounds write of attacker-controlled string into caller's buffer, enabling memory corruption.

- Payout: $250
- Severity: high
- Program: Node.js
- Found by: tniessen
- Disclosed: 2020-07-02
- CVE: CVE-2020-8174
- Write-up quality: 7/10
- Original: https://hackerone.com/reports/784186
- Library page: https://bugbountylibrary.com/r/h1%3A784186
- Tags: area:oss domain:oss impact:dos impact:rce kind:bounty platform:hackerone sev:high tech:nodejs technique:source-review vuln:memory-corruption

**Target:** Node.js N-API native addon API (napi_get_value_string_latin1/utf8/utf16)
**Root cause:** bufsize is size_t; bufsize-1 underflows when bufsize==0, so min(string_length, bufsize-1) becomes string_length and the full string is copied; then buf[copied] writes one more byte past the buffer.
**Steps:**
1. Write native addon calling `napi_get_value_string_latin1(env, info[0], buf, 0, nullptr)` with `char buf[1]` (or malloc(0) result).
2. Load addon from JS and call `binding.test('attacker-controlled string')`.
3. Observe stack smashing / abort; string contents overwrite adjacent memory.
**How found:** Code review of N-API string getter implementation noticing the unsigned bufsize-1 underflow and the unconditional buf[copied] write.
**Exploitation:** Attacker controls the string passed to the N-API call; with bufsize==0 the full string plus terminator is written past the caller's buffer, allowing heap/stack corruption and potentially code injection if the string contains crafted bytes.
**Insight:** When auditing C APIs taking (buf, bufsize), check the bufsize==0 path: unsigned subtraction underflow and the trailing NUL write are common OOB primitives even when callers 'should' pass NULL.

## Proof of concept (copied exactly from the original report)

**C++ PoC calling napi_get_value_string_latin1 with bufsize 0**

```
Napi::Value Test(const Napi::CallbackInfo& info) {
  char buf[1];
  // This should be a valid call, e.g., due to a malloc(0).
  napi_get_value_string_latin1(info.Env(), info[0], buf, 0, nullptr);
  return info.Env().Undefined();
}
```

**JS script triggering the buffer overflow**

```
const binding = require('bindings')('validation');
console.log(binding.test('this could be code that might later be executed'));
```

