uber / uber/h3

replace `sprintf` with `snprintf`

Open
#774 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C
Stars
6.5k
Forks
627
Avg merge
3d 21h
Merged PRs (30d)
6

Description

Question

The h3ToString function uses sprintf(). Is it possible / worth replacing with snprintf() ?

H3Error H3_EXPORT(h3ToString)(H3Index h, char *str, size_t sz) {
    // An unsigned 64 bit integer will be expressed in at most
    // 16 digits plus 1 for the null terminator.
    if (sz < 17) {
        // Buffer is potentially not large enough.
        return E_MEMORY_BOUNDS;
    }
    sprintf(str, "%" PRIx64, h);   // <-- replace with `snprintf(str, sizeof(str), "%" PRIx64, h);` ?
    return E_SUCCESS;
}

For example, as noted in https://rules.sonarsource.com/c/RSPEC-6069/,

When using sprintf , it’s up to the developer to make sure the size of the buffer to be written to is large enough to avoid buffer overflows. Buffer overflows can cause the program to crash at a minimum. At worst, a carefully crafted overflow can cause malicious code to be executed.

(I'm not a full-on C-programmer, so it may be the case that the sz < 17, and the H3Index h (uint64_t) themselves guarantee this overflow won't occur?)


Usecase / Background

I'm building an R library using h3, but upcoming versions of R* won't accept sprintf in compiled code due to the security risk.

* Not strictly R itself, but rather the official repositry of R packagse, CRAN

Use of sprintf and vsprintf is regarded as a potential security risk and warned about on some platforms.82 (including macOS as from version 13).

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with h3ToString in src/h3lib/lib/h3Index.c, especially the existing sz < 17 check and sprintf call. Verify that the string output remains correct and that the change removes the sprintf use without altering the function's return behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
c
Domain
api
Issue type
Refactor
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.