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

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

Avoid 'gets()'. This function does not consider buffer boundaries and can lead to buffer overflows. Use 'fgets()' or 'gets_s()' instead.

Run Locally

Run in CI

Defintion

rules:
  - id: insecure-use-gets-fn
    pattern: gets(...)
    message: Avoid 'gets()'. This function does not consider buffer boundaries and
      can lead to buffer overflows. Use 'fgets()' or 'gets_s()' instead.
    metadata:
      cwe:
        - "CWE-676: Use of Potentially Dangerous Function"
      references:
        - https://us-cert.cisa.gov/bsi/articles/knowledge/coding-practices/fgets-and-gets_s
      category: security
      technology:
        - c
      confidence: MEDIUM
      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: ERROR

Examples

insecure-use-gets-fn.c

#include <stdio.h>

int DST_BUFFER_SIZE = 120;

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

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