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

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

Avoid using 'scanf()'. This function, when used improperly, does not consider buffer boundaries and can lead to buffer overflows. Use 'fgets()' instead for reading input.

Run Locally

Run in CI

Defintion

rules:
  - id: insecure-use-scanf-fn
    pattern: scanf(...)
    message: Avoid using 'scanf()'. This function, when used improperly, does not
      consider buffer boundaries and can lead to buffer overflows. Use 'fgets()'
      instead for reading input.
    metadata:
      cwe:
        - "CWE-676: Use of Potentially Dangerous Function"
      references:
        - http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
      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-scanf-fn.c

#include <stdio.h>

int DST_BUFFER_SIZE = 120;

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

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