c.lang.security.insecure-use-string-copy-fn.insecure-use-string-copy-fn

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

Finding triggers whenever there is a strcpy or strncpy used. This is an issue because strcpy does not affirm the size of the destination array and strncpy will not automatically NULL-terminate strings. This can lead to buffer overflows, which can cause program crashes and potentially let an attacker inject code in the program. Fix this by using strcpy_s instead (although note that strcpy_s is an optional part of the C11 standard, and so may not be available).

Run Locally

Run in CI

Defintion

rules:
  - id: insecure-use-string-copy-fn
    pattern-either:
      - pattern: strcpy(...)
      - pattern: strncpy(...)
    message: Finding triggers whenever there is a strcpy or strncpy used. This is an
      issue because strcpy does not affirm the size of the destination array and
      strncpy will not automatically NULL-terminate strings. This can lead to
      buffer overflows, which can cause program crashes and potentially let an
      attacker inject code in the program. Fix this by using strcpy_s instead
      (although note that strcpy_s is an optional part of the C11 standard, and
      so may not be available).
    metadata:
      cwe:
        - "CWE-676: Use of Potentially Dangerous Function"
      references:
        - https://cwe.mitre.org/data/definitions/676
        - https://nvd.nist.gov/vuln/detail/CVE-2019-11365
      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-string-copy-fn.c

#include <stdio.h>

int DST_BUFFER_SIZE = 120;

int bad_strcpy(src, dst) {
    n = DST_BUFFER_SIZE;
    if ((dst != NULL) && (src != NULL) && (strlen(dst)+strlen(src)+1 <= n))
    {
        // ruleid: insecure-use-string-copy-fn
        strcpy(dst, src);

        // ruleid: insecure-use-string-copy-fn
        strncpy(dst, src, 100);
    }
}

int main() {
   printf("Hello, World!");
   return 0;
}