c.lang.security.insecure-use-strtok-fn.insecure-use-strtok-fn

Community Favorite
profile photo of semgrepsemgrep
Author
46,010
Download Count*

Avoid using 'strtok()'. This function directly modifies the first argument buffer, permanently erasing the delimiter character. Use 'strtok_r()' instead.

Run Locally

Run in CI

Defintion

rules:
  - id: insecure-use-strtok-fn
    pattern: strtok(...)
    message: Avoid using 'strtok()'. This function directly modifies the first
      argument buffer, permanently erasing the delimiter character. Use
      'strtok_r()' instead.
    metadata:
      cwe:
        - "CWE-676: Use of Potentially Dangerous Function"
      references:
        - https://wiki.sei.cmu.edu/confluence/display/c/STR06-C.+Do+not+assume+that+strtok%28%29+leaves+the+parse+string+unchanged
        - https://man7.org/linux/man-pages/man3/strtok.3.html#BUGS
        - https://stackoverflow.com/a/40335556
      category: security
      technology:
        - c
      confidence: LOW
      subcategory:
        - audit
      likelihood: LOW
      impact: HIGH
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - Dangerous Method or Function
    languages:
      - c
    severity: WARNING

Examples

insecure-use-strtok-fn.c

#include <stdio.h>

int DST_BUFFER_SIZE = 120;

int bad_code() {
    char str[DST_BUFFER_SIZE];
    fgets(str, DST_BUFFER_SIZE, stdin);
    // ruleid:insecure-use-strtok-fn
    strtok(str, " ");
    printf("%s", str);
    return 0;
}

int main() {
    char str[DST_BUFFER_SIZE];
    char dest[DST_BUFFER_SIZE];
    fgets(str, DST_BUFFER_SIZE, stdin);
    // ok:insecure-use-strtok-fn
    strtok_r(str, " ", *dest);
    printf("%s", str);
    return 0;
}
}