feat(sast): vendored MIT semgrep packs and a guard against registry rules (#492) #504

Merged
sharang merged 1 commits from feat/492-vendor-semgrep-packs into main 2026-10-06 12:22:51 +00:00
473 changed files with 50690 additions and 116 deletions

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 raptor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+38
View File
@@ -0,0 +1,38 @@
0xdea semgrep-rules (C/C++)
===========================
Upstream: https://github.com/0xdea/semgrep-rules
Commit: dae50da6e6e629750f1daec73a01ef9206a372ab
Version: v2.0.0 + 20 commits (2026-09-25)
Licence: MIT
Copyright: Copyright (c) 2022 raptor (Marco Ivaldi)
Prüfwerk runs these rules with its own semgrep invocation (--metrics=off,
local files only). upstream/ holds the selected files unchanged, with
their semgrep tests. pack.yaml is what the agent runs: the same rules with
ids prefixed by '0xdea-', re-serialised into one file, without
the rules listed below. Both are produced by scripts/vendor-semgrep-rules.py.
Selected from upstream: rules/c/**
Rules in the pack: 35 (from 49 files)
Not selected:
- rules/noisy/: upstream marks these unsuitable for general use
Left out
--------
- 0xdea-raptor-argv-envp-access (rules/c/argv-envp-access.yaml): 43 hits on every argv/getenv read; an audit aid, not a weakness
- 0xdea-raptor-format-string-bugs (rules/c/format-string-bugs.yaml): FP storm: 61 hits in lwIP, all literal formats joined with a macro ("%s"NEWLINE); our cra-ai-20-c-non-literal-format-string covers the real case
- 0xdea-raptor-high-entropy-assignment (rules/c/high-entropy-assignment.yaml): 14 hits, sampled hits are base64 tables and exception-name strings; gitleaks covers committed secrets
- 0xdea-raptor-integer-truncation (rules/c/integer-truncation.yaml): 23 hits in lwIP, sampled hits assign small constants (`x = 1`)
- 0xdea-raptor-interesting-api-calls (rules/c/interesting-api-calls.yaml): FP storm: 718 hits in lwIP; lists every call of an "interesting" API for a manual audit
- 0xdea-raptor-mismatched-memory-management (rules/c/mismatched-memory-management.yaml): 36 hits in lwIP, sampled hits are plain matching malloc/free pairs
- 0xdea-raptor-missing-break-in-switch (rules/c/missing-break-in-switch.yaml): intended fallthrough in FreeRTOS-Kernel and lwIP; a review hint by upstream's own description (code quality / audit aid), not a weakness
- 0xdea-raptor-missing-default-in-switch (rules/c/missing-default-in-switch.yaml): 22 hits; a review hint by upstream's own description (code quality / audit aid), not a weakness
- 0xdea-raptor-missing-return (rules/c/missing-return.yaml): FP storm: 1514 hits in FreeRTOS-Kernel (port macros); a review hint by upstream's own description (code quality / audit aid), not a weakness
- 0xdea-raptor-pointer-subtraction (rules/c/pointer-subtraction.yaml): 16 hits in lwIP, all `len = end - start` length arithmetic
- 0xdea-raptor-signed-unsigned-conversion (rules/c/signed-unsigned-conversion.yaml): FP storm: 221 hits in FreeRTOS-Kernel and lwIP, nearly all benign casts
- 0xdea-raptor-suspicious-assert (rules/c/suspicious-assert.yaml): FP storm: 176 hits in FreeRTOS-Kernel and lwIP (configASSERT/LWIP_ASSERT on sizes)
- 0xdea-raptor-typos (rules/c/typos.yaml): FP storm: 989 hits in FreeRTOS-Kernel and lwIP; a review hint by upstream's own description (code quality / audit aid), not a weakness
- 0xdea-raptor-write-into-stack-buffer (rules/c/write-into-stack-buffer.yaml): 27 hits on every write into a stack array; an audit aid, not a weakness
+1
View File
@@ -0,0 +1 @@
https://github.com/0xdea/semgrep-rules dae50da6e6e629750f1daec73a01ef9206a372ab
File diff suppressed because it is too large. Load diff
+281
View File
@@ -0,0 +1,281 @@
[
{
"id": "0xdea-raptor-command-injection",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-78"
},
{
"id": "0xdea-raptor-double-free",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-415"
},
{
"id": "0xdea-raptor-incorrect-order-setuid-setgid",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-696"
},
{
"id": "0xdea-raptor-incorrect-unsigned-comparison",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-697"
},
{
"id": "0xdea-raptor-incorrect-use-of-free",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-590"
},
{
"id": "0xdea-raptor-incorrect-use-of-memset",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-683"
},
{
"id": "0xdea-raptor-incorrect-use-of-sizeof",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-467"
},
{
"id": "0xdea-raptor-incorrect-use-of-strncat",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-787"
},
{
"id": "0xdea-raptor-insecure-api-access-stat",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-367"
},
{
"id": "0xdea-raptor-insecure-api-alloca",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-676"
},
{
"id": "0xdea-raptor-insecure-api-ato",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-839"
},
{
"id": "0xdea-raptor-insecure-api-gets",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-242"
},
{
"id": "0xdea-raptor-insecure-api-mktemp-tmpnam-tempnam",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-377"
},
{
"id": "0xdea-raptor-insecure-api-rand-srand",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-338"
},
{
"id": "0xdea-raptor-insecure-api-scanf",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-676"
},
{
"id": "0xdea-raptor-insecure-api-signal",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-364"
},
{
"id": "0xdea-raptor-insecure-api-sprintf-vsprintf",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-676"
},
{
"id": "0xdea-raptor-insecure-api-strcpy-strcat",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-676"
},
{
"id": "0xdea-raptor-integer-wraparound",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-190"
},
{
"id": "0xdea-raptor-memory-address-exposure",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-209"
},
{
"id": "0xdea-raptor-mismatched-memory-management-cpp",
"languages": [
"cpp"
],
"cwe": "CWE-762"
},
{
"id": "0xdea-raptor-off-by-one",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-193"
},
{
"id": "0xdea-raptor-overlapping-source-destination",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-1260"
},
{
"id": "0xdea-raptor-putenv-stack-var",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-686"
},
{
"id": "0xdea-raptor-regex-dos",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-1333"
},
{
"id": "0xdea-raptor-ret-stack-address",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-562"
},
{
"id": "0xdea-raptor-unchecked-ret-malloc",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-252"
},
{
"id": "0xdea-raptor-unchecked-ret-scanf",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-252"
},
{
"id": "0xdea-raptor-unchecked-ret-setuid-seteuid",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-252"
},
{
"id": "0xdea-raptor-unsafe-ret-snprintf-vsnprintf",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-131"
},
{
"id": "0xdea-raptor-unsafe-ret-strlcpy-strlcat",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-131"
},
{
"id": "0xdea-raptor-unsafe-strlen",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-190"
},
{
"id": "0xdea-raptor-unterminated-string-strncpy",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-170"
},
{
"id": "0xdea-raptor-use-after-free",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-416"
},
{
"id": "0xdea-raptor-use-of-source-size-in-copy",
"languages": [
"c",
"cpp"
],
"cwe": "CWE-806"
}
]
@@ -0,0 +1,28 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
#define CMD_MAX 512
int main(int argc, char **argv)
{
char cmd[CMD_MAX] = "/usr/bin/cat ";
// ruleid: raptor-argv-envp-access
strcat(cmd, argv[1]);
system(cmd);
return 0;
}
int main(int c, char **v)
{
char cmd[CMD_MAX] = "/usr/bin/cat ";
// this should arguably trigger the detection, but it doesn't because the rule is currently extremely
// simple and only looks for "argv" and "envp" as variable names, not for the actual parameters of main()
// todoruleid: raptor-argv-envp-access
strcat(cmd, v[1]);
system(cmd);
return 0;
}
@@ -0,0 +1,31 @@
rules:
- id: raptor-argv-envp-access
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Other Security
likelihood: LOW
impact: LOW
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-15: External Control of System or Configuration Setting"
owasp:
- A05:2025 - Injection
references:
- https://www.gnu.org/software/libc/manual/html_node/Program-Arguments.html
message: >-
The program accesses command-line arguments or environment variables,
which are controlled by potential attackers.
severity: INFO
languages:
- c
- cpp
patterns:
- pattern-either:
- pattern: argv
- pattern: envp
@@ -0,0 +1,103 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void invoke1(char *string)
{
char buf[] = "uname -a; id";
// ok: raptor-command-injection
system(buf);
// ok: raptor-command-injection
system("whoami");
// ruleid: raptor-command-injection
system(string);
}
void invoke2(char *string)
{
char buf[] = "uname -a; id";
// ok: raptor-command-injection
popen(buf, "r");
// ok: raptor-command-injection
popen("whoami", "r");
// ruleid: raptor-command-injection
popen(string, "r");
}
int send_mail(char *user)
{
char buf[1024];
FILE *fp;
snprintf(buf, sizeof(buf), "/usr/bin/sendmail -s \"hi\" %s", user);
// ruleid: raptor-command-injection
fp = popen(buf, "w");
if (fp == NULL)
return 1;
// ...
}
enum
{
BUFFERSIZE = 512
};
void test_001(const char *input)
{
char cmdbuf[BUFFERSIZE];
int len_wanted = snprintf(cmdbuf, BUFFERSIZE,
"any_cmd '%s'", input);
if (len_wanted >= BUFFERSIZE)
{
/* Handle error */
}
else if (len_wanted < 0)
{
/* Handle error */
}
// ruleid: raptor-command-injection
else if (system(cmdbuf) == -1)
{
/* Handle error */
}
}
void test_002(const char *input)
{
char cmdbuf[BUFFERSIZE];
int len_wanted = snprintf(cmdbuf, BUFFERSIZE,
"any_cmd '%s'", input);
// ruleid: raptor-command-injection
system(cmdbuf);
}
void test_003(const char *input)
{
// ok: raptor-command-injection
storer->store_binary(Clocks->system());
}
void test_004(const char *input)
{
// ok: raptor-command-injection
storer->store_binary(Clocks::system());
// ok: raptor-command-injection
double passed_server_time = max(Clocks::system() - old_server_time, 0.0);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,40 @@
rules:
- id: raptor-command-injection
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Command Injection
likelihood: MEDIUM
impact: HIGH
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')"
- "CWE-88: Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')"
- "CWE-676: Use of Potentially Dangerous Function"
owasp:
- A05:2025 - Injection
references:
- https://g.co/kgs/PCHQjJ
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
message: >-
The software constructs an OS command using externally-influenced input,
but it does not neutralize or incorrectly neutralizes special elements
that could modify the intended OS command.
severity: ERROR
languages:
- c
- cpp
# NOTE: add path injection rule for `execlp`, `execvp`, and `execvP`.
# NOTE: add argument injection (e.g., in the `exec` functions family).
patterns:
- pattern-either:
- pattern: system(...)
- pattern: popen(...)
- pattern: p2open(...)
- pattern: wordexp(...)
- pattern-not: $_("...", ...)
@@ -0,0 +1,96 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
#define MEMSIZE 256
#define BUFSIZE1 128
#define BUFSIZE2 256
void alloc_and_free1()
{
int bailout = 1;
char *ptr = (char *)malloc(MEMSIZE);
// this should be caught but it isn't, due to a documented limitation in semgrep
// https://semgrep.dev/docs/writing-rules/pattern-syntax/#ellipses-and-statement-blocks
// todoruleid: raptor-double-free
if (bailout)
free(ptr);
free(ptr);
// ruleid: raptor-double-free
free(ptr);
}
void alloc_and_free2()
{
char *ptr = (char *)malloc(MEMSIZE);
free(ptr);
ptr = NULL;
// ok: raptor-double-free
free(ptr);
}
void alloc_and_free3()
{
char *ptr = (char *)malloc(MEMSIZE);
free(ptr);
ptr = (char *)malloc(MEMSIZE);
// ok: raptor-double-free
free(ptr);
}
void double_free(int argc, char **argv)
{
char *buf1R1;
char *buf2R1;
char *buf1R2;
buf1R1 = (char *)malloc(BUFSIZE2);
buf2R1 = (char *)malloc(BUFSIZE2);
free(buf1R1);
free(buf2R1);
buf1R2 = (char *)malloc(BUFSIZE1);
strncpy(buf1R2, argv[1], BUFSIZE1 - 1);
// ruleid: raptor-double-free
free(buf2R1);
free(buf1R2);
}
Packet *getNextPacket()
{
// ...
Packet *y = (Packet *)malloc(1024);
retval = waitForPacket(y);
if (retval == OK)
{
return y;
}
else
{
return NULL;
}
}
int bad()
{
// ...
free(logData);
pkt = getNextPacket();
if (!pkt)
{
return NULL;
}
logPktData(pkt);
// ruleid: raptor-double-free
free(logData);
processPacket(pkt);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,55 @@
rules:
- id: raptor-double-free
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: HIGH
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-415: Double Free"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://github.com/struct/mms
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
- https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples
- https://dustri.org/b/playing-with-weggli.html
message: >-
The software calls free() twice on the same memory address, potentially
leading to memory corruption. This corruption can cause the program to
crash or cause two later calls to malloc() to return the same pointer.
severity: ERROR
languages:
- c
- cpp
# NOTE: C++ `delete` and `delete[]` operators and custom wrappers to `free` are not covered.
# NOTE: `realloc` is not covered.
# NOTE: variations on the `free` argument are not covered.
patterns:
- pattern: |
$FREE1($PTR);
...
$FREE2($PTR);
- pattern-not: |
$FREE1($PTR);
...
$PTR = ...;
...
$FREE2($PTR);
- metavariable-pattern:
metavariable: $FREE1
pattern: free
# more patterns could be added here to cover other ways to free memory
- metavariable-pattern:
metavariable: $FREE2
pattern: free
# more patterns could be added here to cover other ways to free memory
# improve output readability
- focus-metavariable: $FREE2
@@ -0,0 +1,108 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <syslog.h>
#define BUFSIZE 256
void build_string(char *string)
{
char buf[BUFSIZE];
// ruleid: raptor-format-string-bugs
snprintf(buf, BUFSIZE, string);
// ok: raptor-format-string-bugs
snprintf(buf, BUFSIZE, "%s", string);
}
void print_stuff(char *string)
{
char buf[BUFSIZE];
// ruleid: raptor-format-string-bugs
printf(string);
// ok: raptor-format-string-bugs
printf("%s\n", string);
}
void log_stuff(char *string)
{
char buf[BUFSIZE];
// ruleid: raptor-format-string-bugs
syslog(LOG_ERR, string);
// ok: raptor-format-string-bugs
syslog(LOG_ERR, "%s", string);
}
void log_error(char *fmt, ...)
{
char buf[BUFSIZE];
va_list ap;
va_start(ap, fmt);
// ruleid: raptor-format-string-bugs
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
// ruleid: raptor-format-string-bugs
syslog(LOG_NOTICE, buf);
}
void printWrapper(char *string)
{
// ruleid: raptor-format-string-bugs
printf(string);
}
namespace basic_tests
{
void test_001()
{
const char *env_001 = getenv("PATH");
// ruleid: raptor-format-string-bugs
printf(env_001, 1);
// ok: raptor-format-string-bugs
printf("%s", env_001);
// ruleid: raptor-format-string-bugs
scanf(env_001, &d);
}
}
int test_002(int argc, char **argv)
{
int d = 0;
// ruleid: raptor-format-string-bugs
scanf(argv[1], &d);
}
int test_003(int argc, char **argv)
{
static const size_t n_quads = 300;
sord_free(NULL); // Shouldn't crash
SordWorld *world = sord_world_new();
// ok: raptor-format-string-bugs
fprintf(stderr, "expected ");
// ruleid: raptor-format-string-bugs
fprintf(stderr, argv[1]);
return finished(world, sord, EXIT_SUCCESS);
}
int main(int argc, char **argv)
{
char buf[5012];
memcpy(buf, argv[1], 5012);
printWrapper(argv[1]);
return 0;
}
@@ -0,0 +1,122 @@
rules:
- id: raptor-format-string-bugs
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: HIGH
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-134: Use of Externally-Controlled Format String"
owasp:
- A05:2025 - Injection
references:
- https://julianor.tripod.com/bc/formatstring-1.2.pdf
- http://phrack.org/issues/70/13.html#article
- https://g.co/kgs/PCHQjJ
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
message: >-
The software uses a function that accepts a format string as an argument,
but the format string originates from an external source. This can lead
to buffer overflows, denial of service, or data representation problems.
severity: ERROR
languages:
- c
- cpp
# NOTE: generic `va_list` matching for custom wrappers is not covered.
# NOTE: `dprintf` in C++ has a different signature; this rule may cause false positives with it.
# NOTE: `#define` format specifiers are not excluded due to Semgrep limitations; perhaps we could implement this with symbolic propagation (Semgrep Pro experimental feature)?
# NOTE: some obsolete Microsoft-specific functions, such as `_ftprintf`, `_sntprintf`, `_snwprintf`, `_sntscanf`, etc., are not covered.
pattern-either:
# format string in 1st arg
- patterns:
- pattern-either:
# printf family
- pattern: printf(...)
- pattern: vprintf(...)
- pattern: wprintf(...)
- pattern: vwprintf(...)
- pattern: vcprintf(...)
- pattern: vcwprintf(...)
- pattern: vscprintf(...)
- pattern: vscwprintf(...)
- pattern: printk(...)
# scanf family
- pattern: scanf(...)
- pattern: __isoc99_scanf(...)
- pattern: vscanf(...)
- pattern: __isoc99_vscanf(...)
- pattern: wscanf(...)
- pattern: vwscanf(...)
# err/warn family
- pattern: warn(...)
- pattern: vwarn(...)
- pattern: warnx(...)
- pattern: vwarnx(...)
- pattern-not: $_("...", ...)
- pattern-not: $_(gettext(...), ...)
- pattern-not: $_(dgettext(...), ...)
- pattern-not: $_(dcgettext(...), ...)
# format string in 2nd arg
- patterns:
- pattern-either:
# printf family
- pattern: fprintf(...)
- pattern: vfprintf(...)
- pattern: fwprintf(...)
- pattern: vfwprintf(...)
- pattern: sprintf(...)
- pattern: vsprintf(...)
- pattern: asprintf(...)
- pattern: vasprintf(...)
- pattern: dprintf(...)
- pattern: vdprintf(...)
- pattern: wsprintf(...)
# scanf family
- pattern: fscanf(...)
- pattern: __isoc99_fscanf(...)
- pattern: vfscanf(...)
- pattern: __isoc99_vfscanf(...)
- pattern: fwscanf(...)
- pattern: vfwscanf(...)
- pattern: sscanf(...)
- pattern: __isoc99_sscanf(...)
- pattern: vsscanf(...)
- pattern: __isoc99_vsscanf(...)
- pattern: swscanf(...)
- pattern: vswscanf(...)
# syslog family
- pattern: syslog(...)
- pattern: vsyslog(...)
# err/warn family
- pattern: err(...)
- pattern: verr(...)
- pattern: errx(...)
- pattern: verrx(...)
- pattern: warnc(...)
- pattern: vwarnc(...)
- pattern-not: $_($_, "...", ...)
- pattern-not: $_($_, gettext(...), ...)
- pattern-not: $_($_, dgettext(...), ...)
- pattern-not: $_($_, dcgettext(...), ...)
# format string in 3rd arg
- patterns:
- pattern-either:
# printf family
- pattern: snprintf(...)
- pattern: vsnprintf(...)
- pattern: swprintf(...)
- pattern: vswprintf(...)
# err/warn family
- pattern: errc(...)
- pattern: verrc(...)
- pattern-not: $_($_, $_, "...", ...)
- pattern-not: $_($_, $_, gettext(...), ...)
- pattern-not: $_($_, $_, dgettext(...), ...)
- pattern-not: $_($_, $_, dcgettext(...), ...)
@@ -0,0 +1,20 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
int hush_hush()
{
// ruleid: raptor-high-entropy-assignment
char *secret = "d3a447630194bd4b";
// ok: raptor-high-entropy-assignment
char *public = "Hello, world!";
// ...
return 0;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,34 @@
rules:
- id: raptor-high-entropy-assignment
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Hard-coded Secrets
likelihood: LOW
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-540: Inclusion of Sensitive Information in Source Code"
owasp:
- A06:2025 - Insecure Design
references:
- https://semgrep.dev/docs/writing-rules/metavariable-analysis
- https://github.com/semgrep/semgrep/pull/4672
message: >-
Entropy, or randomness, is a common approach for detecting secret
strings. If an assignment has high entropy, it might involve a
secret that should not be accessible to users.
severity: INFO
languages:
- c
- cpp
patterns:
- pattern: $_ = "$X"
- metavariable-analysis:
analyzer: entropy
metavariable: $X
@@ -0,0 +1,101 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <unistd.h>
void drop_priv_bad()
{
// ruleid: raptor-incorrect-order-setuid-setgid
setuid(getuid());
setgid(getgid());
}
void drop_priv_ok()
{
// ok: raptor-incorrect-order-setuid-setgid
setgid(getgid());
setuid(getuid());
}
void bad1()
{
// ruleid: raptor-incorrect-order-setuid-setgid
seteuid(getuid());
// ...
setuid(getuid());
}
void good1()
{
// ok: raptor-incorrect-order-setuid-setgid
seteuid(getuid());
// ...
seteuid(0);
// ...
setuid(getuid());
}
void bad2()
{
int user1 = 500, user2 = 501;
/* become user1 */
// ruleid: raptor-incorrect-order-setuid-setgid
seteuid(user1);
process_log1();
/* become user2 */
seteuid(user2);
process_log2();
/* become root again */
seteuid(0);
}
void good2()
{
int user1 = 500, user2 = 501;
/* become user1 */
// ok: raptor-incorrect-order-setuid-setgid
seteuid(user1);
process_log1();
/* become user2 */
seteuid(0);
seteuid(user2);
process_log2();
/* become root again */
seteuid(0);
}
void drop_priv_conditional_bad(int uid, int gid)
{
// ruleid: raptor-incorrect-order-setuid-setgid
if (uid != -1 && setuid(uid))
{
fprintf(stderr, "Failed to set uid\n");
}
if (gid != -1)
{
setgid(gid);
}
}
void drop_priv_conditional_ok(int uid, int gid)
{
// ok: raptor-incorrect-order-setuid-setgid
if (gid != -1 && setgid(gid))
{
fprintf(stderr, "Failed to set gid\n");
}
if (uid != -1)
{
setuid(uid);
}
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,94 @@
rules:
- id: raptor-incorrect-order-setuid-setgid
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Improper Authorization
likelihood: MEDIUM
impact: HIGH
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-696: Incorrect Behavior Order"
owasp:
- A01:2025 - Broken Access Control
references:
- https://www.usenix.org/legacy/events/sec02/full_papers/chen/chen.pdf
- https://g.co/kgs/PCHQjJ
- https://github.com/struct/mms
message: >-
A compromised process might be able to regain elevated group privileges
if set(e)gid() is called after set(e)uid(). A similar case is when
privileges are temporarily dropped with seteuid() and then setuid() or
seteuid() are called from while under unprivileged user.
severity: ERROR
languages:
- c
- cpp
pattern-either:
# setuid/setgid
- patterns:
- pattern: |
<... setuid(...) ...>;
...
<... setgid(...) ...>;
- pattern-not: |
<... setuid(0) ...>;
...
<... setgid(...) ...>;
# seteuid/setegid
- patterns:
- pattern: |
<... seteuid(...) ...>;
...
<... setegid(...) ...>;
- pattern-not: |
<... seteuid(0) ...>;
...
<... setegid(...) ...>;
- pattern-not-inside: |
<... seteuid(...) ...>;
...
<... seteuid(0) ...>;
...
<... setegid(...) ...>;
# seteuid/setuid
- patterns:
- pattern: |
<... seteuid(...) ...>;
...
<... setuid(...) ...>;
- pattern-not: |
<... seteuid(0) ...>;
...
<... setuid(...) ...>;
- pattern-not-inside: |
<... seteuid(...) ...>;
...
<... seteuid(0) ...>;
...
<... setuid(...) ...>;
# seteuid/seteuid
- patterns:
- pattern: |
<... seteuid(...) ...>;
...
<... seteuid(...) ...>;
- pattern-not: |
<... seteuid(0) ...>;
...
<... seteuid(...) ...>;
- pattern-not: |
<... seteuid(...) ...>;
...
<... seteuid(0) ...>;
- pattern-not-inside: |
<... seteuid(...) ...>;
...
<... seteuid(0) ...>;
...
<... seteuid(...) ...>;
@@ -0,0 +1,42 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
int bad1()
{
size_t uvar;
// ruleid: raptor-incorrect-unsigned-comparison
if (uvar < 0)
return 1;
return 0;
}
int bad2()
{
size_t uvar;
// ruleid: raptor-incorrect-unsigned-comparison
if (uvar <= 0)
return 1;
return 0;
}
int good1()
{
size_t uvar;
// ok: raptor-incorrect-unsigned-comparison
if (uvar > 0)
return 1;
return 0;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,52 @@
rules:
- id: raptor-incorrect-unsigned-comparison
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Improper Validation
likelihood: LOW
impact: MEDIUM
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-697: Incorrect Comparison"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
message: >-
Checking if an unsigned variable is negative makes no sense and is
usually a good indication that something is probably wrong with the
code.
severity: WARNING
languages:
- c
- cpp
# NOTE: some types are not covered.
# NOTE: incorrect unsigned assigments are not covered.
pattern-either:
# < (always false)
- pattern: (unsigned short $_) < 0
- pattern: (unsigned short int $_) < 0
- pattern: (unsigned int $_) < 0
- pattern: (unsigned long $_) < 0
- pattern: (unsigned long int $_) < 0
- pattern: (size_t $_) < 0
# <=
- pattern: (unsigned short $_) <= 0
- pattern: (unsigned short int $_) <= 0
- pattern: (unsigned int $_) <= 0
- pattern: (unsigned long $_) <= 0
- pattern: (unsigned long int $_) <= 0
- pattern: (size_t $_) <= 0
# >= (always true)
- pattern: (unsigned short $_) >= 0
- pattern: (unsigned short int $_) >= 0
- pattern: (unsigned int $_) >= 0
- pattern: (unsigned long $_) >= 0
- pattern: (unsigned long int $_) >= 0
- pattern: (size_t $_) >= 0
@@ -0,0 +1,55 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#define SIZE 256
void wrong()
{
record_t bar[MAX_SIZE];
/* do something interesting with bar */
// ruleid: raptor-incorrect-use-of-free
free(bar);
}
void right()
{
record_t *bar = (record_t *)malloc(MAX_SIZE * sizeof(record_t));
/* do something interesting with bar */
// ok: raptor-incorrect-use-of-free
free(bar);
}
int check_auth(char *login, char *passwd)
{
char *cpass;
char *message;
int i = 0;
int stat = STATUS_INVALID;
struct passwd *pwd;
if ((pwd = getpwnam(login)) == NULL)
return (STATUS_UNKNOWN);
hisuid = pwd->pw_uid;
haveuid = 1;
if (hisuid < MIN_UNIX_UID)
return (STATUS_BLOCKED);
if (authenticate(login, passwd, &i, &message) == 0)
{
stat = STATUS_OK;
}
// ruleid: raptor-incorrect-use-of-free
free(&message);
return (stat);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,86 @@
rules:
- id: raptor-incorrect-use-of-free
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: HIGH
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-590: Free of Memory not on the Heap"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_spirit.c
message: >-
The software calls free() on a pointer to memory that has a short
lifetime and was not allocated using associated heap allocation
functions such as malloc(), calloc(), or realloc().
severity: ERROR
languages:
- c
- cpp
# NOTE: this rule only covers `free` called on stack-allocated buffers (and possibly static variables); it does not cover other instances of `free` called on non-heap-allocated buffers; it also does not cover `alloca` and custom wrappers to `free`.
# NOTE: multi-dimensional arrays and other ways to create an array are not covered.
# NOTE: refer also to `raptor-mismatched-memory-management.yaml`.
pattern-either:
- patterns:
- pattern: free($PTR)
- pattern-either:
# array
- pattern-inside: |
$_ $PTR[$_];
...
- pattern-inside: |
$_ $PTR[$_] = ...;
...
- pattern-inside: |
$_ $PTR[] = ...;
...
# pointer to array
- pattern-inside: |
$_ $ARR[$_];
...
$PTR = $ARR;
...
- pattern-inside: |
$_ $ARR[$_] = ...;
...
$PTR = $ARR;
...
- pattern-inside: |
$_ $ARR[] = ...;
...
$PTR = $ARR;
...
- patterns:
# address of local variable
- pattern: free(&$VAR)
- pattern-either:
- pattern-inside: |
$_ $VAR;
...
- pattern-inside: |
$_ $VAR = ...;
...
- pattern-inside: |
$_ $VAR[$_];
...
- pattern-inside: |
$_ $VAR[$_] = ...;
...
- pattern-inside: |
$_ $VAR[] = ...;
...
- pattern-inside: |
$_ * $VAR;
...
- pattern-inside: |
$_ * $VAR = ...;
...
@@ -0,0 +1,55 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#define SIZE 256
int test1()
{
char buf[1024];
// ruleid: raptor-incorrect-use-of-memset
memset(buf, sizeof(buf), 0);
// ruleid: raptor-incorrect-use-of-memset
memset(buf, sizeof(buf), 'A');
// ok: raptor-incorrect-use-of-memset
memset(buf, 0, sizeof(buf));
return 0;
}
int test2()
{
char buf[SIZE];
// ruleid: raptor-incorrect-use-of-memset
memset(buf, SIZE, 0);
// ok: raptor-incorrect-use-of-memset
memset(buf, 0, SIZE);
return 0;
}
void test3()
{
// ...
if (!StartServiceCtrlDispatcher(steDispatchTable))
{
char szString[1024];
// ruleid: raptor-incorrect-use-of-memset
memset(szString, sizeof(szString), '\0');
SvcFormatMessage(szString, sizeof(szString));
SvcDebugOut(szString, 0);
}
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,37 @@
rules:
- id: raptor-incorrect-use-of-memset
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Mishandled Sensitive Information
likelihood: MEDIUM
impact: MEDIUM
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-683: Function Call With Incorrect Order of Arguments"
owasp:
- A04:2025 - Cryptographic Failures
references:
- https://lkml.org/lkml/2009/11/11/336
- https://bugs.mysql.com/bug.php?id=23181
message: >-
The invocation of memset() is easy to get wrong. The second argument
is the character and the third argument is the size, but sometimes
these arguments are in the wrong order. This results in a no-op.
severity: ERROR
languages:
- c
- cpp
# NOTE: refer also to `c.lang.security.insecure-use-memset.insecure-use-memset` and `cpp.lang.correctness.memset-removal.memset-removal` for a different potential flaw involving `memset` optimization.
pattern-either:
- pattern: memset($_, $_, 0)
- pattern: memset($_, $_, '\0')
- pattern: memset($_, sizeof(...), $_)
- pattern: memset_explicit($_, $_, 0)
- pattern: memset_explicit($_, $_, '\0')
- pattern: memset_explicit($_, sizeof(...), $_)
@@ -0,0 +1,184 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void bad1()
{
double *foo;
// ruleid: raptor-incorrect-use-of-sizeof
foo = (double *)malloc(sizeof(foo));
}
void good1()
{
double *foo;
// ok: raptor-incorrect-use-of-sizeof
foo = (double *)malloc(sizeof(*foo));
}
void bad2(char *buf)
{
size_t size;
// ruleid: raptor-incorrect-use-of-sizeof
size = sizeof(buf);
}
void good2()
{
char buf[256];
size_t size;
// ok: raptor-incorrect-use-of-sizeof
size = sizeof(buf);
}
void bad3()
{
AnObj *o = (AnObj *)malloc(sizeof(AnObj));
// ruleid: raptor-incorrect-use-of-sizeof
memset(o, 0x0, sizeof(o));
}
char *read_username(int sockfd)
{
char *buffer, *style, userstring[1024];
int i;
buffer = (char *)malloc(1024);
if (!buffer)
{
error("buffer allocation failed: %m");
return NULL;
}
if (read(sockfd, userstring, sizeof(userstring) - 1) <= 0)
{
free(buffer);
error("read failure: %m");
return NULL;
}
userstring[sizeof(userstring) - 1] = '\0';
style = strchr(userstring, ':');
if (style)
*style++ = '\0';
sprintf(buffer, "username=%.32s", userstring);
if (style)
// ruleid: raptor-incorrect-use-of-sizeof
snprintf(buffer, sizeof(buffer) - strlen(buffer) - 1, ", style=%s\n", style);
return buffer;
}
char *username = "admin";
char *pass = "password";
int AuthenticateUser(char *inUser, char *inPass)
{
// ruleid: raptor-incorrect-use-of-sizeof
printf("Sizeof username = %d\n", sizeof(username));
// ruleid: raptor-incorrect-use-of-sizeof
printf("Sizeof pass = %d\n", sizeof(pass));
// ruleid: raptor-incorrect-use-of-sizeof
if (strncmp(username, inUser, sizeof(username)))
{
printf("Auth failure of username using sizeof\n");
return (AUTH_FAIL);
}
// ruleid: raptor-incorrect-use-of-sizeof
if (!strncmp(pass, inPass, sizeof(pass)))
{
printf("Auth success of password using sizeof\n");
return (AUTH_SUCCESS);
}
else
{
printf("Auth fail of password using sizeof\n");
return (AUTH_FAIL);
}
}
// https://github.com/openresty/memc-nginx-module/commit/1e5e8655b3783d29dec1a9941bb6571989cf7dbb
ngx_int_t
ngx_http_memc_create_incr_decr_cmd_request(ngx_http_request_t *r)
{
size_t len;
ngx_buf_t *b;
ngx_http_memc_ctx_t *ctx;
ngx_chain_t *cl;
uintptr_t escape;
ngx_http_variable_value_t *key_vv;
ngx_http_variable_value_t *value_vv;
ctx = ngx_http_get_module_ctx(r, ngx_http_memc_module);
/* prepare the "key" argument */
key_vv = ctx->memc_key_vv;
if (key_vv == NULL || key_vv->not_found || key_vv->len == 0)
{
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
"the \"$memc_key\" variable is not set");
return NGX_ERROR;
}
escape = 2 * ngx_escape_uri(NULL, key_vv->data, key_vv->len,
NGX_ESCAPE_MEMCACHED);
/* prepare the "value" argument */
value_vv = ctx->memc_value_vv;
/* XXX validate if $memc_value_vv is a valid uint64 string */
// this should be caught but it isn't, due to a known issue in semgrep
// https://github.com/semgrep/semgrep/issues/11327
// todoruleid: raptor-incorrect-use-of-sizeof
len = ctx->cmd_str.len + sizeof(' ') + key_vv->len + escape + sizeof(' ') + value_vv->len + sizeof(CRLF) - 1;
b = ngx_create_temp_buf(r->pool, len);
if (b == NULL)
{
return NGX_ERROR;
}
cl = ngx_alloc_chain_link(r->pool);
if (cl == NULL)
{
return NGX_ERROR;
}
// ...
return NGX_OK;
}
int main(int argc, char **argv)
{
int authResult;
if (argc < 3)
{
ExitError("Usage: Provide a username and password");
}
authResult = AuthenticateUser(argv[1], argv[2]);
if (authResult != AUTH_SUCCESS)
{
ExitError("Authentication failed");
}
else
{
DoAuthenticatedTask(argv[1]);
}
return 0;
}
@@ -0,0 +1,121 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <cstdint>
#include <cstddef>
#include <iostream>
struct Foo
{
uint64_t a;
uint8_t b;
size_t get_size() const
{
// ruleid: raptor-incorrect-use-of-sizeof
return sizeof(this);
}
size_t get_size() const
{
// ok: raptor-incorrect-use-of-sizeof
return sizeof(*this);
}
};
void test_001_fn(int arr[])
{
// ruleid: raptor-incorrect-use-of-sizeof
for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i)
{
arr[i] = 0;
}
// ruleid: raptor-incorrect-use-of-sizeof
for (size_t i = 0; i < sizeof(arr) / 2; ++i)
{
arr[i] = 0;
}
// ruleid: raptor-incorrect-use-of-sizeof
for (size_t i = 0; i < 3 * sizeof(arr); ++i)
{
arr[i] = 0;
}
}
void test_001(int arr[])
{
// ruleid: raptor-incorrect-use-of-sizeof
for (size_t i = 0; i < sizeof(arr); ++i)
{
arr[i] = 0;
}
}
void test_002()
{
const FooType *foo_ptr = get_foo();
// ruleid: raptor-incorrect-use-of-sizeof
std::cout << sizeof(foo_ptr);
// ruleid: raptor-incorrect-use-of-sizeof
std::cout << sizeof(foo_ptr + 0);
// ruleid: raptor-incorrect-use-of-sizeof
std::cout << sizeof(0 + foo_ptr);
// ruleid: raptor-incorrect-use-of-sizeof
std::cout << (sizeof(foo_ptr) / sizeof(foo_ptr[0]));
// ok: raptor-incorrect-use-of-sizeof
std::cout << sizeof(*foo_ptr);
}
void test_002_pad()
{
int a = 1;
const FooType *foo_ptr = get_foo();
// ruleid: raptor-incorrect-use-of-sizeof
std::cout << sizeof(foo_ptr);
// ruleid: raptor-incorrect-use-of-sizeof
std::cout << (sizeof(foo_ptr) / sizeof(foo_ptr[0]));
// ok: raptor-incorrect-use-of-sizeof
std::cout << sizeof(*foo_ptr);
}
void test_002_atofat()
{
int a = 1;
const FooType **foo_ptr = get_foo();
// ok: raptor-incorrect-use-of-sizeof
std::cout << sizeof(*foo_ptr);
// ok: raptor-incorrect-use-of-sizeof
std::cout << (sizeof(*foo_ptr) / sizeof(foo_ptr[0]));
// ok: raptor-incorrect-use-of-sizeof
std::cout << sizeof(**foo_ptr);
}
void test_003(void *foo, int *int_ptr)
{
// ruleid: raptor-incorrect-use-of-sizeof
std::cout << sizeof(int_ptr);
// ruleid: raptor-incorrect-use-of-sizeof
std::cout << (sizeof(int_ptr) / sizeof(int_ptr[0]));
// ok: raptor-incorrect-use-of-sizeof
std::cout << sizeof(*int_ptr);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,78 @@
rules:
- id: raptor-incorrect-use-of-sizeof
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-467: Use of sizeof() on a Pointer Type"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
- https://github.com/struct/mms
- https://dustri.org/b/playing-with-weggli.html
- https://mastodon.gamedev.place/@amonakov/111577826195014479
- https://github.com/semgrep/semgrep/issues/11327
message: >-
The code calls sizeof() on a pointer type, which always returns
the wordsize (8 on 64-bit architectures). This can produce an
unexpected result if the programmer intended to determine how
much memory has been allocated.
severity: WARNING
languages:
- c
- cpp
# NOTE: another relevant pattern would be `sizeof('...')`, but unfortunately that's currently not supported by Semgrep.
pattern-either:
# type-based patterns (some types are missing)
- patterns:
- pattern: sizeof((char * $_))
- pattern-not: sizeof("...")
# NOTE: sizeof of character literals is still not supported by Semgrep as of 2025-11-22
# - pattern: sizeof('...')
- pattern: sizeof((int * $_))
- pattern: sizeof((float * $_))
- pattern: sizeof((double * $_))
# other patterns
- patterns:
- pattern-either:
- pattern: sizeof($PTR)
- pattern: sizeof($PTR + $_)
- pattern: sizeof($_ + $PTR)
- pattern-either:
- pattern-inside: |
$_ * $PTR;
...
- pattern-inside: |
$_ * $PTR = ...;
...
# function calls
- patterns:
- pattern-either:
- pattern: sizeof($PTR)
- pattern: sizeof($PTR + $_)
- pattern: sizeof($_ + $PTR)
- pattern-either:
- pattern-inside: |
$_ $_(..., $_ * $PTR, ...) {
...
}
- pattern-inside: |
$_ $_(..., $_ $PTR[$_], ...) {
...
}
- pattern-inside: |
$_ $_(..., $_ $PTR[], ...) {
...
}
# c++ `this` pattern
- pattern: sizeof(this)
@@ -0,0 +1,62 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
int copy_data(char *username)
{
char buf[1024];
strcpy(buf, "username is: ");
// ruleid: raptor-incorrect-use-of-strncat
strncat(buf, username, sizeof(buf));
log("%s\n", buf);
return 0;
}
int copy_data2(char *username)
{
char buf[1024];
strcpy(buf, "username is: ");
// ruleid: raptor-incorrect-use-of-strncat
strncat(buf, username, 1024);
log("%s\n", buf);
return 0;
}
int copy_data3(char *username)
{
char buf[1024];
strcpy(buf, "username is: ");
// ruleid: raptor-incorrect-use-of-strncat
strncat(buf, username, sizeof(buf) - strlen(buf));
log("%s\n", buf);
return 0;
}
int good(char *username)
{
char buf[1024];
strcpy(buf, "username is: ");
// ok: raptor-incorrect-use-of-strncat
strncat(buf, username, sizeof(buf) - strlen(buf) - 1);
log("%s\n", buf);
return 0;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,50 @@
rules:
- id: raptor-incorrect-use-of-strncat
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: HIGH
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-787: Out-of-bounds Write"
- "CWE-193: Off-by-one Error"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
message: >-
The strncat() function is nearly as dangerous as strcat(), in that it's
quite easy to misuse. The first common mistake is supplying the size of
the entire buffer instead of the size remaining in the buffer. A more
subtle mistake can be made: the size parameter needs to be the amount of
space left in the buffer less one; otherwise, the NUL byte is written
one byte past the end of the buffer.
severity: ERROR
languages:
- c
- cpp
pattern-either:
# size of array
- patterns:
- pattern: strncat($DST, $_, $LEN)
- pattern-either:
- pattern-inside: |
$_ $DST[$LEN];
...
- pattern-inside: |
$_ $DST[$LEN] = ...;
...
# sizeof operator
- pattern: strncat($DST, $_, sizeof($DST))
# strlen function
- pattern: strncat($DST, $_, strlen($DST))
# off-by-one
# see also off-by-one.yaml for a slightly different pattern
- pattern: strncat($DST, $_, sizeof($DST) - strlen($DST))
@@ -0,0 +1,150 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#define MEMSIZE 256
void bad1()
{
// ruleid: raptor-insecure-api-access-stat
int res = access("/tmp/userfile", R_OK);
if (res != 0)
die("access");
int fd = open("/tmp/userfile", O_RDONLY);
// ...
}
void bad2(char *file)
{
struct stat statb;
int fd;
errno = 0;
// ruleid: raptor-insecure-api-access-stat
if (lstat(file, &statb) < 0)
goto out;
if (!(statb.st_mode & S_IFREG) || statb.st_mode & 077)
goto out;
if ((fd = open(file, O_RDWR | O_SYNC, 0)) < 0)
goto out;
}
void bad3(char *fname)
{
struct stat stbl;
int fd = open(fname, O_RDONLY);
if (fd == -1)
perror("open");
// ruleid: raptor-insecure-api-access-stat
if (lstat(fname, &stbl) != 0)
die("file not there");
if (!S_ISREG(stbl.st_mode))
die("its a symlink");
// ...
}
void test_001()
{
const char *original_key = "path/to/file/filename";
const char *mirror_key = "path/to/another/file/filename";
// ruleid: raptor-insecure-api-access-stat
if ((access(original_key, F_OK) == 0) && (access(mirror_key, F_OK) == 0))
{
copy_file("/bin/cp %s %s", original_key, mirror_key);
unlink(original_key);
}
}
void test_002()
{
const char *original_key = "path/to/file/filename";
// ruleid: raptor-insecure-api-access-stat
if (access(original_key, W_OK) == 0)
{
FILE *fp = fopen(original_key, "wb");
}
}
void test_001_stack_overflow()
{
struct stat buf;
FILE *fp;
char data[2560];
// ruleid: raptor-insecure-api-access-stat
if (stat(file.c_str(), &buf) == 0)
{
// Open the file for reading
fp = fopen(file.c_str(), "r");
if (fp == NULL)
{
char message[2560];
sprintf(message, "File '%s' Cound Not be Opened", file.c_str());
// DISPLAY_MSG_ERROR( this, message, "GetFileContents", "System" );
throw message;
}
// Read the file
MvString s, ss;
while (fgets(data, sizeof(data), fp) != (char *)0)
{
s = data;
s.trimBoth();
if (s.compare(0, 5, "GROUP") == 0)
{
// size_t t = s.find_last_of( ":" );
size_t t = s.find(":");
if (t != string::npos)
{
ss = s.substr(t + 1).c_str();
ss.trimBoth();
ss = ss.substr(1, ss.length() - 3).c_str();
group_list.push_back(ss);
}
}
}
// Close the file
fclose(fp);
}
}
void ok()
{
int fd = open("file.txt", O_RDONLY);
if (fd == -1)
{
perror("open");
return -1;
}
struct stat st;
// ok: raptor-insecure-api-access-stat
if (fstat(fd, &st) == -1)
{
perror("fstat");
close(fd);
return -1;
}
// Now safely use st.st_mode, st.st_size, etc. on the already-open fd
// ...
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,39 @@
rules:
- id: raptor-insecure-api-access-stat
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Dangerous Method or Function
likelihood: MEDIUM
impact: MEDIUM
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
- https://labs.snyk.io/resources/leaky-vessels-container-vuln-deep-dive/
message: >-
The software checks the state of a resource before using it, but the
resource's state can change between the check and the use in a way that
invalidates the results of the check. This can cause the software to
perform invalid actions when the resource is in an unexpected state.
severity: WARNING
languages:
- c
- cpp
# NOTE: `_stat` and `_lstat` are not covered.
# NOTE: refer also to `cpp.lang.security.filesystem.*` for stricter check/action patterns.
pattern-either:
- pattern: access(...)
- pattern: faccessat(...)
- pattern: faccessat2(...)
- pattern: stat(...)
- pattern: lstat(...)
- pattern: fstatat(...)
@@ -0,0 +1,42 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
#define MEMSIZE 256
void allocate_memory1()
{
// ruleid: raptor-insecure-api-alloca
char *buf = alloca(MEMSIZE);
// ...
}
void allocate_memory2()
{
// ok: raptor-insecure-api-alloca
char *buf = malloc(MEMSIZE);
// ...
}
void allocate_memory2()
{
int end_limit = get_nmbr_obj_from_db();
int i;
int *base = NULL;
int *p = base;
for (i = 0; i < end_limit; i++)
{
// ruleid: raptor-insecure-api-alloca
*p = alloca(sizeof(int *));
p = *p;
}
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,32 @@
rules:
- id: raptor-insecure-api-alloca
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Dangerous Method or Function
likelihood: MEDIUM
impact: HIGH
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-676: Use of Potentially Dangerous Function"
- "CWE-1325: Improperly Controlled Sequential Memory Allocation"
owasp:
- A06:2025 - Insecure Design
references:
- https://nullprogram.com/blog/2019/10/28/
- https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples
message: >-
Use of alloca() is unsafe because it cannot ensure that the pointer
returned points to a valid and usable block of memory. The allocation
made may exceed the bounds of the stack, or even go further into other
objects in memory, and alloca() cannot determine such an error.
severity: ERROR
languages:
- c
- cpp
pattern: alloca(...)
@@ -0,0 +1,22 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
int converter_bad(const char *numstr)
{
// ruleid: raptor-insecure-api-ato
return atoi(numstr);
}
int converter_good(const char *numstr)
{
// ok: raptor-insecure-api-ato
return strtol(numstr, NULL, 10);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,39 @@
rules:
- id: raptor-insecure-api-ato
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Dangerous Method or Function
likelihood: LOW
impact: MEDIUM
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-839: Numeric Range Comparison Without Minimum Check"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://rules.sonarsource.com/c/type/Bug/RSPEC-989
- https://wiki.sei.cmu.edu/confluence/display/c/ERR34-C.+Detect+errors+when+converting+a+string+to+a+number
- https://github.com/vixie/cron/commit/9cc8ab1087bb9ab861dd5595c41200683c9f6712
message: >-
The atoi(), atol(), atof(), and similar functions don't handle errors.
They don't check for integer overflow and can return a negative value.
They have undefined behavior if the value of the result cannot be
represented. They return 0 (or 0.0) if the string does not represent
an integer (or decimal), which is indistinguishable from a correctly
formatted, zero-denoting input string.
severity: INFO
languages:
- c
- cpp
# NOTE: some function variants are missing.
pattern-either:
- pattern: atoi(...)
- pattern: atol(...)
- pattern: atof(...)
- pattern: atoll(...)
@@ -0,0 +1,43 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#define BUFSIZE 256
void get_string()
{
char buf[BUFSIZE];
// ruleid: raptor-insecure-api-gets
gets(buf);
}
void test_001()
{
char buf[BUFFER_SIZE];
// ruleid: raptor-insecure-api-gets
if (gets(buf) == NULL)
{
// ...
}
}
void foo()
{
char buf[64];
// ruleid: raptor-insecure-api-gets
gets(buf);
}
void foo()
{
char buf[64];
// ok: raptor-insecure-api-gets
fgets(buf, 63, stdin);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,30 @@
rules:
- id: raptor-insecure-api-gets
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Dangerous Method or Function
likelihood: HIGH
impact: HIGH
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-242: Use of Inherently Dangerous Function"
- "CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
message: >-
The gets() function is always unsafe because it does not perform bounds
checking on the size of its input. An attacker can easily send
arbitrarily-sized input to gets() and overflow the destination buffer.
severity: ERROR
languages:
- c
- cpp
pattern: gets(...)
@@ -0,0 +1,28 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <unistd.h>
void open_tmpfile1(char *path)
{
// ruleid: raptor-insecure-api-mktemp-tmpnam-tempnam
char *filename = mktemp(path);
FILE *tmp = fopen(filename, "wb+");
// do something
}
void open_tmpfile2(char *path, char *data, size_t len)
{
// ok: raptor-insecure-api-mktemp-tmpnam-tempnam
int fd = mkstemp(path);
write(fd, data, len);
// do something
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,37 @@
rules:
- id: raptor-insecure-api-mktemp-tmpnam-tempnam
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Dangerous Method or Function
likelihood: MEDIUM
impact: MEDIUM
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-377: Insecure Temporary File"
- "CWE-367: Time-of-check Time-of-use (TOCTOU) Race Condition"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
message: >-
Creating and using insecure temporary files can leave application and
system data vulnerable to attack.
severity: WARNING
languages:
- c
- cpp
pattern-either:
- pattern: mktemp(...)
- pattern: tmpnam(...)
- pattern: tempnam(...)
- pattern: tmpnam_r(...)
# - pattern: _mktemp(...)
# - pattern: _tmpnam(...)
# - pattern: _tempnam(...)
# - pattern: GetTempFileName(...)
@@ -0,0 +1,56 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum
{
len = 12
};
void func_bad(void)
{
char id[len];
int r;
int num;
// ...
// ruleid: raptor-insecure-api-rand-srand
r = rand();
num = snprintf(id, len, "ID%-d", r);
// ...
}
void func_good(void)
{
char id[len];
int r;
int num;
// ...
struct timespec ts;
if (timespec_get(&ts, TIME_UTC) == 0)
{
/* handle error */
}
// ok: raptor-insecure-api-rand-srand
srandom(ts.tv_nsec ^ ts.tv_sec);
// ...
// ok: raptor-insecure-api-rand-srand
r = random();
num = snprintf(id, len, "ID%-d", r);
// ...
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,44 @@
rules:
- id: raptor-insecure-api-rand-srand
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Cryptographic Issues
likelihood: MEDIUM
impact: MEDIUM
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)"
- "CWE-330: Use of Insufficiently Random Values"
owasp:
- A04:2025 - Cryptographic Failures
references:
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
message: >-
The rand() PRNG should not be used in applications intended to be
portable when good randomness is needed. Instead, the use of random()
is recommended.
severity: WARNING
languages:
- c
- cpp
# NOTE: `rand_r` and other non-standard PRNGs are not covered.
# NOTE: improperly seeded strong PRNGs are not covered.
# NOTE: refer also to `cpp.lang.security.rng.*`, `cpp.lang.security.crypto.*`, and `gitlab.flawfinder.*`.
pattern-either:
- pattern: rand(...)
- pattern: srand(...)
- pattern: drand48(...)
- pattern: erand48(...)
- pattern: lrand48(...)
- pattern: nrand48(...)
- pattern: mrand48(...)
- pattern: jrand48(...)
- pattern: lcong48(...)
- pattern: srand48(...)
- pattern: seed48(...)
@@ -0,0 +1,236 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#define BUFSIZE 256
#define FMT "whatever"
void read_string(char *string)
{
char buf[BUFSIZE];
int number;
char fmt[] = "whatever";
// ruleid: raptor-insecure-api-scanf
scanf("%s", buf);
// ok: raptor-insecure-api-scanf
scanf("%d", &number);
// ruleid: raptor-insecure-api-scanf
sscanf(string, "string: %s", buf);
// ruleid: raptor-insecure-api-scanf
scanf(FMT, buf);
// ruleid: raptor-insecure-api-scanf
scanf(fmt, buf);
// ruleid: raptor-insecure-api-scanf
scanf(buf);
}
void test_func()
{
char last_name[20];
printf("Enter your last name: ");
// ruleid: raptor-insecure-api-scanf
scanf("%s", last_name);
}
int read_ident(int sockfd)
{
int sport, cport;
char user[32], rtype[32], addinfo[32];
char buffer[1024];
if (read(sockfd, buffer, sizeof(buffer)) <= 0)
{
perror("read: %m");
return 1;
}
buffer[sizeof(buffer) - 1] = '\0';
// ruleid: raptor-insecure-api-scanf
sscanf(buffer, "%d:%d:%s:%s:%s", &sport, &cport, rtype, user, addinfo);
// ...
}
// https://github.com/pedrib/PoC/blob/master/advisories/Pwn2Own/Tokyo_2019/tokyo_drift/tokyo_drift.md
undefined4 sa_setBlockName(char *block_name, int len)
{
int scanf_res;
char *__src;
char scanf_str[1024];
undefined4 scanf_int;
scanf_int = 0;
scanf_str._0_4_ = 0;
memset(scanf_str + 4, 0, 0x3fc);
print_debug(3, "%s(%d);\n", "sa_setBlockName", 0x42d);
if (len != 0)
{
// ruleid: raptor-insecure-api-scanf
scanf_res = sscanf(block_name, "%d%s", &scanf_int, scanf_str);
/* if ((scanf_res == 2) && (__src = strstr(block_name, s), __src != NULL)) {
// ...
} */
}
return 0;
}
// https://www.synacktiv.com/en/publications/pwn2own-austin-2021-defeating-the-netgear-r6700v3.html
int updating_database(int a1, const char *update_server)
{
// ...
char line[1020]; // [sp+894h] [bp-4FCh] BYREF
char db_checksum_val[256]; // [sp+D94h] [bp+4h] BYREF
char db_checksum[256]; // [sp+E94h] [bp+104h] BYREF
// ...
v7 = fopen("/tmp/circleinfo.txt", "r");
if (v7)
{
line[0] = 0;
while (fgets(line, 1024, v7))
{
// ruleid: raptor-insecure-api-scanf
if (sscanf(line, "%s %s", db_checksum, db_checksum_val) == 2 && !strcmp(db_checksum, "db_checksum"))
{
// ...
break;
}
}
}
return 0;
}
void test_003(void)
{
char buf[BUFFER_SIZE];
// ruleid: raptor-insecure-api-scanf
if (1 != fscanf(stdin, "%s", buf))
{
// ...
}
}
void test_003_valist(void)
{
char buf[BUFFER_SIZE];
// ruleid: raptor-insecure-api-scanf
if (1 != fscanf(stdin, "%d%d%s", 1, 2, buf))
{
// ...
}
}
void test_003_stmt(void)
{
char buf[BUFFER_SIZE];
// ruleid: raptor-insecure-api-scanf
fscanf(stdin, "%d%d%s", 1, 2, buf);
}
void test_004(void)
{
char buf[BUFFER_SIZE];
// ok: raptor-insecure-api-scanf
if (1 != fscanf(stdin, "%d", buf))
{
// ...
}
}
void test_007(wchar_t *name)
{
char filename[128];
// ruleid: raptor-insecure-api-scanf
fwscanf(stdin, L"foo%sbar", filename);
}
void foo()
{
char buf[128];
int n;
// ruleid: raptor-insecure-api-scanf
fscanf(stdin, "%dfoo%sbar", n, buf);
// ruleid: raptor-insecure-api-scanf
fscanf(stdin, "%sbar", n, buf);
// ruleid: raptor-insecure-api-scanf
fscanf(stdin, "foo%s", n, buf);
}
void foo()
{
char buf[128];
int n;
// ok: raptor-insecure-api-scanf
fscanf(stdin, "%dfoo%10sbar", n, buf);
}
void foo()
{
char buf[128];
int n;
// sized format specifiers aren't parsed yet
// todoruleid: raptor-insecure-api-scanf
fscanf(stdin, "%dfoo%1024sbar", n, buf);
}
void foo()
{
char buf[128];
// ruleid: raptor-insecure-api-scanf
fscanf(stdin, "%sfoo%%s", buf);
// ruleid: raptor-insecure-api-scanf
fscanf(stdin, "%sfoo%%%s", buf);
}
void foo()
{
char buf[64];
va_list ap;
va_start(ap, buf);
// ruleid: raptor-insecure-api-scanf
vscanf("%s", ap);
va_end(ap);
}
void foo()
{
char buf[64];
va_list ap;
va_start(ap, buf);
// ruleid: raptor-insecure-api-scanf
vfscanf(stdin, "%s", ap);
va_end(ap);
}
void foo(char *str)
{
char buf[0];
// ruleid: raptor-insecure-api-scanf
sscanf(str, "%s", buf);
// ok: raptor-insecure-api-scanf
sscanf("constant string", "%s", buf);
va_list ap;
va_start(ap, fmt);
// ruleid: raptor-insecure-api-scanf
vsscanf(str, "%s", buf);
va_end(ap);
va_list ap;
va_start(ap, fmt);
// ok: raptor-insecure-api-scanf
vsscanf("constant string", "%s", buf);
va_end(ap);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,61 @@
rules:
- id: raptor-insecure-api-scanf
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Dangerous Method or Function
likelihood: HIGH
impact: HIGH
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-676: Use of Potentially Dangerous Function"
- "CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')"
- "CWE-787: Out-of-bounds Write"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
message: >-
A buffer overflow condition exists when a program attempts to put
more data in a buffer than it can hold, or when a program attempts to
put data in a memory area outside of the boundaries of a buffer.
severity: ERROR
languages:
- c
- cpp
patterns:
- pattern-either:
- pattern: scanf($FMT, ...)
- pattern: __isoc99_scanf($FMT, ...)
- pattern: vscanf($FMT, ...)
- pattern: __isoc99_vscanf($FMT, ...)
- pattern: fscanf($_, $FMT, ...)
- pattern: __isoc99_fscanf($_, $FMT, ...)
- pattern: vfscanf($_, $FMT, ...)
- pattern: __isoc99_vfscanf($_, $FMT, ...)
- pattern: sscanf($_, $FMT, ...)
- pattern: __isoc99_sscanf($_, $FMT, ...)
- pattern: vsscanf($_, $FMT, ...)
- pattern: __isoc99_vsscanf($_, $FMT, ...)
- pattern: wscanf($FMT, ...)
- pattern: vwscanf($FMT, ...)
- pattern: fwscanf($_, $FMT, ...)
- pattern: vfwscanf($_, $FMT, ...)
- pattern: swscanf($_, $FMT, ...)
- pattern: vswscanf($_, $FMT, ...)
# exclude string literals as source
- pattern-not: sscanf("...", $FMT, ...)
- pattern-not: __isoc99_sscanf("...", $FMT, ...)
- pattern-not: vsscanf("...", $FMT, ...)
- pattern-not: __isoc99_vsscanf("...", $FMT, ...)
- pattern-not: swscanf("...", $FMT, ...)
- pattern-not: vswscanf("...", $FMT, ...)
- metavariable-regex:
metavariable: $FMT
# NOTE: some format string specifiers are not handled
regex: '(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)'
@@ -0,0 +1,47 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
char *logMessage;
void handler(int sigNum)
{
syslog(LOG_NOTICE, "%s\n", logMessage);
free(logMessage);
sleep(10);
exit(0);
}
int bad_main(int argc, char *argv[])
{
logMessage = strdup(argv[1]);
// ruleid: raptor-insecure-api-signal
signal(SIGHUP, handler);
// ruleid: raptor-insecure-api-signal
signal(SIGTERM, handler);
sleep(10);
return 0;
}
int good_main(int argc, char *argv[])
{
logMessage = strdup(argv[1]);
struct sigaction sa;
sa.sa_handler = handler;
// ok: raptor-insecure-api-signal
sigaction(SIGHUP, &sa, NULL);
// ok: raptor-insecure-api-signal
sigaction(SIGTERM, &sa, NULL);
sleep(10);
return 0;
}
@@ -0,0 +1,35 @@
rules:
- id: raptor-insecure-api-signal
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Dangerous Method or Function
likelihood: MEDIUM
impact: MEDIUM
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-364: Signal Handler Race Condition"
- "CWE-479: Signal Handler Use of a Non-reentrant Function"
- "CWE-828: Signal Handler with Functionality that is not Asynchronous-Safe"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://lcamtuf.coredump.cx/signals.txt
message: >-
The signal() API should be regarded as deprecated. When possible,
sigaction() should be used instead, because it allows to precisely
specify the desired behavior in case two signals arrive shortly after
each other thus preventing many race conditions.
severity: WARNING
languages:
- c
- cpp
pattern-either:
- pattern: signal(...)
- pattern: gsignal(...)
- pattern: ssignal(...)
@@ -0,0 +1,72 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#define BUFSIZE 256
#define FMT "whatever"
void copy_string(char *string, int number)
{
char buf[BUFSIZE];
char fmt[] = "whatever";
// ruleid: raptor-insecure-api-sprintf-vsprintf
sprintf(buf, "string: %s\n", string);
// ok: raptor-insecure-api-sprintf-vsprintf
sprintf(buf, "number: %d\n", number);
// ruleid: raptor-insecure-api-sprintf-vsprintf
sprintf(buf, FMT, string);
// ruleid: raptor-insecure-api-sprintf-vsprintf
sprintf(buf, fmt, string);
// ruleid: raptor-insecure-api-sprintf-vsprintf
sprintf(buf, string);
}
static void
WriteToLog(jrun_request *r, const char *szFormat, ...)
{
server_rec *s = (server_rec *)r->context;
va_list list;
char szBuf[2048];
strcpy(szBuf, r->stringRep);
va_start(list, szFormat);
// ruleid: raptor-insecure-api-sprintf-vsprintf
vsprintf(strchr(szBuf, '\0'), szFormat, list);
va_end(list);
#if MODULE_MAGIC_NUMBER > 19980401
ap_log_error(APLOG_MARK, APLOG_NOERRNO | APLOG_NOTICE, s, "%s", szBuf);
#else
log_error(szBuf, s);
#endif
#ifdef WIN32
strcat(szBuf, "\r\n");
OutputDebugString(szBuf);
#endif
}
void test_005(const char *name)
{
char filename[128];
// ruleid: raptor-insecure-api-sprintf-vsprintf
sprintf(filename, "%s", name);
}
void test_006(const char *name)
{
char filename[128];
// ok: raptor-insecure-api-sprintf-vsprintf
sprintf(filename, "%d", name);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,38 @@
rules:
- id: raptor-insecure-api-sprintf-vsprintf
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Dangerous Method or Function
likelihood: HIGH
impact: HIGH
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-676: Use of Potentially Dangerous Function"
- "CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')"
- "CWE-787: Out-of-bounds Write"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
message: >-
A buffer overflow condition exists when a program attempts to put
more data in a buffer than it can hold, or when a program attempts to
put data in a memory area outside of the boundaries of a buffer.
severity: ERROR
languages:
- c
- cpp
patterns:
- pattern-either:
- pattern: sprintf($_, $FMT, ...)
- pattern: vsprintf($_, $FMT, ...)
- metavariable-regex:
metavariable: $FMT
# NOTE: some format string specifiers are not handled
regex: '(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)'
@@ -0,0 +1,150 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#define BUFSIZE 256
void copy_append_string1(char *string1, char *string2)
{
char buf[BUFSIZE];
// ruleid: raptor-insecure-api-strcpy-strcat
strcpy(buf, string1);
// ruleid: raptor-insecure-api-strcpy-strcat
strcat(buf, string2);
}
int copy_append_string2(const char *string1, const char *string2,
char *buf, size_t bufsz)
{
if (!string1 || !string2 || !buf || bufsz == 0)
return -1;
// ok: raptor-insecure-api-strcpy-strcat
if (strlcpy(buf, string1, bufsz) >= bufsz)
return -1; // truncation
// ok: raptor-insecure-api-strcpy-strcat
if (strlcat(buf, string2, bufsz) >= bufsz)
return -1; // truncation
return 0;
}
void copy_string(char *string)
{
char buf[BUFSIZE];
// ruleid: raptor-insecure-api-strcpy-strcat
stpcpy(buf, string);
}
void test_func()
{
struct hostent *clienthp;
char hostname[MAX_LEN];
// ...
int count = 0;
for (count = 0; count < MAX_CONNECTIONS; count++)
{
int clientlen = sizeof(struct sockaddr_in);
int clientsocket = accept(serversocket, (struct sockaddr *)&clientaddr, &clientlen);
if (clientsocket >= 0)
{
clienthp = gethostbyaddr((char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET);
// ruleid: raptor-insecure-api-strcpy-strcat
strcpy(hostname, clienthp->h_name);
logOutput("Accepted client connection from host ", hostname);
// ...
close(clientsocket);
}
}
close(serversocket);
// ...
}
char *read_command(int sockfd)
{
char username[32], buffer[1024];
int n;
if ((n = read(sockfd, buffer, sizeof(buffer) - 1) <= 0))
return NULL;
buffer[n] = '\0';
switch (buffer[0])
{
case 'U':
// ruleid: raptor-insecure-api-strcpy-strcat
strcpy(username, &buffer[1]);
break;
// ...
}
}
int process_email(char *email)
{
char username[32], domain[128], *delim;
int c;
delim = strchr(email, '@');
if (!delim)
return -1;
*delim++ = '\0';
if (strlen(email) >= sizeof(username))
return -1;
// ruleid: raptor-insecure-api-strcpy-strcat
strcpy(username, email);
if (strlen(delim) >= sizeof(domain))
return -1;
// ruleid: raptor-insecure-api-strcpy-strcat
strcpy(domain, delim);
if (!strchr(delim, '.'))
// ruleid: raptor-insecure-api-strcpy-strcat
strcat(domain, default_domain);
// ...
}
void process_address(int sockfd)
{
char username[256], domain[256], netbuf[256], *ptr;
read_data(sockfd, netbuf, sizeof(netbuf));
ptr = strchr(netbuf, ':');
if (ptr)
*ptr++ = '\0';
// ruleid: raptor-insecure-api-strcpy-strcat
strcpy(username, netbuf);
if (ptr)
// ruleid: raptor-insecure-api-strcpy-strcat
strcpy(domain, ptr);
// ...
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,47 @@
rules:
- id: raptor-insecure-api-strcpy-strcat
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Dangerous Method or Function
likelihood: HIGH
impact: HIGH
confidence: HIGH
technology:
- c
- cpp
cwe:
- "CWE-676: Use of Potentially Dangerous Function"
- "CWE-120: Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')"
- "CWE-787: Out-of-bounds Write"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
message: >-
A buffer overflow condition exists when a program attempts to put
more data in a buffer than it can hold, or when a program attempts to
put data in a memory area outside of the boundaries of a buffer.
severity: ERROR
languages:
- c
- cpp
# NOTE: some functions, such as `_fstrcpy` and `_fstrcat`, are not covered.
patterns:
- pattern-either:
- pattern: strcpy(...)
- pattern: stpcpy(...)
- pattern: strcat(...)
- pattern: wcscpy(...)
- pattern: wcpcpy(...)
- pattern: wcscat(...)
- pattern: _mbscpy(...)
- pattern: _mbscat(...)
- pattern: strccpy(...)
- pattern: strcadd(...)
- pattern: streadd(...)
- pattern: strecpy(...)
- pattern: strtrns(...)
- pattern-not: $_($_, "...", ...)
@@ -0,0 +1,53 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
void assign_int(int int_var)
{
// ruleid: raptor-integer-truncation
char char_var = int_var;
short short_var;
int int_var2;
// ruleid: raptor-integer-truncation
short_var = int_var;
// ok: raptor-integer-truncation
int_var2 = int_var + 1;
}
void assign_long(long long_var)
{
short short_var;
// ruleid: raptor-integer-truncation
int int_var = long_var + 1;
// ruleid: raptor-integer-truncation
short_var = long_var;
// ok: raptor-integer-truncation
long long_var2 = long_var + 1;
}
void test_func()
{
int intPrimitive;
short shortPrimitive;
intPrimitive = (int)(~((int)0) ^ (1 << (sizeof(int) * 8 - 1)));
// ruleid: raptor-integer-truncation
shortPrimitive = intPrimitive;
printf("Int MAXINT: %d\nShort MAXINT: %d\n", intPrimitive, shortPrimitive);
}
// ruleid: raptor-integer-truncation
char func(void)
{
int a = 42;
return a;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,133 @@
rules:
- id: raptor-integer-truncation
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Other Security
likelihood: MEDIUM
impact: MEDIUM
confidence: LOW
technology:
- c
- cpp
cwe:
- "CWE-197: Numeric Truncation Error"
- "CWE-681: Incorrect Conversion between Numeric Types"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
- https://github.com/struct/mms
message: >-
Truncation errors occur when a primitive is cast to a primitive of a
smaller size and data is lost in the conversion. The value cannot be
trusted and the application will be in an undefined state.
severity: WARNING
languages:
- c
- cpp
# NOTE: the deep expression operator is necessary to catch some matches because C/C++ integer promotions do not seem entirely supported by Semgrep; this may generate lots of false positives.
# NOTE: some types (e.g., pointers) and use cases (e.g., comparisons) are not covered.
pattern-either:
# char: assignments
- patterns:
- pattern-either:
- pattern: (char $_) = <... (short $_) ...>
- pattern: (char $_) = <... (short int $_) ...>
- pattern: (char $_) = <... (unsigned short $_) ...>
- pattern: (char $_) = <... (unsigned short int $_) ...>
- pattern: (char $_) = <... (int $_) ...>
- pattern: (char $_) = <... (unsigned $_) ...>
- pattern: (char $_) = <... (unsigned int $_) ...>
- pattern: (char $_) = <... (long $_) ...>
- pattern: (char $_) = <... (long int $_) ...>
- pattern: (char $_) = <... (unsigned long $_) ...>
- pattern: (char $_) = <... (unsigned long int $_) ...>
- pattern-not: $_ = 0
# char: function return
- patterns:
- pattern-either:
- pattern: |
char $FUN(...)
{
...
return (short $_);
}
- pattern: |
char $FUN(...)
{
...
return (int $_);
}
- pattern: |
char $FUN(...)
{
...
return (long $_);
}
# improve output readability
- focus-metavariable: $FUN
# short: assignments
- patterns:
- pattern-either:
- pattern: (short $_) = <... (unsigned short $_) ...>
- pattern: (short int $_) = <... (unsigned short int $_) ...>
- pattern: (short $_) = <... (int $_) ...>
- pattern: (short $_) = <... (unsigned $_) ...>
- pattern: (short int $_) = <... (unsigned int $_) ...>
- pattern: (short $_) = <... (long $_) ...>
- pattern: (short int $_) = <... (long int $_) ...>
- pattern: (short $_) = <... (unsigned long $_) ...>
- pattern: (short int $_) = <... (unsigned long int $_) ...>
- pattern: (unsigned short $_) = <... (int $_) ...>
- pattern: (unsigned short int $_) = <... (unsigned int $_) ...>
- pattern: (unsigned short $_) = <... (long $_) ...>
- pattern: (unsigned short int $_) = <... (long int $_) ...>
- pattern: (unsigned short $_) = <... (unsigned long $_) ...>
- pattern: (unsigned short int $_) = <... (unsigned long int $_) ...>
- pattern-not: $_ = 0
# short: function return
- patterns:
- pattern-either:
- pattern: |
short $FUN(...)
{
...
return (int $_);
}
- pattern: |
short $FUN(...)
{
...
return (long $_);
}
# improve output readability
- focus-metavariable: $FUN
# int: assignments
- patterns:
- pattern-either:
- pattern: (int $_) = <... (unsigned $_) ...>
- pattern: (int $_) = <... (unsigned int $_) ...>
- pattern: (int $_) = <... (long $_) ...>
- pattern: (int $_) = <... (long int $_) ...>
- pattern: (int $_) = <... (unsigned long $_) ...>
- pattern: (int $_) = <... (unsigned long int $_) ...>
- pattern-not: $_ = 0
# int: function return
- patterns:
- pattern: |
int $FUN(...)
{
...
return (long $_);
}
# improve output readability
- focus-metavariable: $FUN
# long: assignments
- patterns:
- pattern-either:
- pattern: (long $_) = <... (unsigned long $_) ...>
- pattern: (long int $_) = <... (unsigned long int $_) ...>
- pattern-not: $_ = 0
@@ -0,0 +1,310 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
#include <stdckdint.h> // C23
void bad1()
{
img_t table_ptr;
int num_imgs;
// ...
num_imgs = get_num_imgs();
// ruleid: raptor-integer-wraparound
table_ptr = (img_t *)malloc(sizeof(img_t) * num_imgs);
// ...
}
int good1(void)
{
int num_imgs = get_num_imgs();
size_t alloc_size;
if (num_imgs <= 0)
return -1;
if (ckd_mul(&alloc_size, (size_t)num_imgs, sizeof(img_t)))
return -1; // overflow
// ok: raptor-integer-wraparound
img_t *table_ptr = malloc(alloc_size);
if (!table_ptr)
return -1;
// ...
free(table_ptr);
return 0;
}
int good2(void)
{
int num_imgs = get_num_imgs();
if (num_imgs <= 0)
return -1;
if ((size_t)num_imgs > SIZE_MAX / sizeof(img_t))
return -1; // overflow
// the rule doesn't currently check for this pattern of overflow prevention, but it arguably should
// todook: raptor-integer-wraparound
img_t *table_ptr = malloc((size_t)num_imgs * sizeof(img_t));
if (!table_ptr)
return -1;
// ...
free(table_ptr);
return 0;
}
// https://vulncat.fortify.com/
void bad2()
{
int nresp = packet_get_int();
if (nresp > 0)
{
// ruleid: raptor-integer-wraparound
response = malloc(nresp * sizeof(char *));
for (int i = 0; i < nresp; i++)
response[i] = packet_get_string(NULL);
}
}
// https://fromdayzerotozeroday.com/
void bad3(n)
{
// ruleid: raptor-integer-wraparound
char *const new_connector = (char *)realloc(parser->m_groupConnector, parser->m_groupSize *= 2);
// ruleid: raptor-integer-wraparound
int *const new_scaff_index = (int *)realloc(dtd->scaffIndex, parser->m_groupSize * sizeof(int));
n *= 2;
// ruleid: raptor-integer-wraparound
char *buf = (char *)malloc(n)
}
u_char *make_table(unsigned int width, unsigned int height, u_char *init_row)
{
unsigned int n;
int i;
u_char *buf;
n = width * height;
// ruleid: raptor-integer-wraparound
buf = (char *)malloc(n);
if (!buf)
return NULL;
for (i = 0; i < height; i++)
memcpy(&buf[i * width], init_row, width);
return buf;
}
// http://www.phrack.org/issues/60/10.html#article
int myfunction(int *array, int len)
{
int *myarray, i;
// ruleid: raptor-integer-wraparound
myarray = malloc(len * sizeof(int));
if (myarray == NULL)
{
return -1;
}
for (i = 0; i < len; i++)
{
myarray[i] = array[i];
}
return myarray;
}
static int
set_cursor(struct tfb_softc *sc, struct wsdisplay_cursor *p)
{
u_int v, index = 0, count = 0, icount = 0;
uint8_t r[2], g[2], b[2], image[512], mask[512];
int error, s;
v = p->which;
if (v & WSDISPLAY_CURSOR_DOCMAP)
{
index = p->cmap.index; // p->cmap.index is u_int
count = p->cmap.count; // p->cmap.count is u_int
// ruleid: raptor-integer-wraparound
if (index >= 2 || (index + count) > 2)
return (EINVAL);
error = copyin(p->cmap.red, &r[index], count);
}
}
void **ht_get_all(ht_t self, int want_key)
{
// ruleid: raptor-integer-wraparound
void **ret = (void **)calloc(self->num_keys + 1, sizeof(void *));
if (ret)
{
void **tail = ret;
size_t i;
for (i = 0; i < self->num_buckets; i++)
{
ht_entry_t curr;
for (curr = self->buckets[i]; curr; curr = curr->next)
{
*tail++ = (want_key ? curr->key : curr->value);
}
}
}
return ret;
}
dl_status dl_start(dl_t self)
{
// ...
plist_t dict = plist_new_dict();
// ...
char *xml = NULL;
uint32_t xml_length = 0;
plist_to_xml(dict, &xml, &xml_length);
plist_free(dict);
size_t length = 16 + xml_length;
// ruleid: raptor-integer-wraparound
char *packet = (char *)calloc(length, sizeof(char));
if (!packet)
{
return DL_ERROR;
}
// ...
}
// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/
CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data,
const char *password,
unsigned char *ntbuffer /* 21 bytes */)
{
size_t len = strlen(password);
// ruleid: raptor-integer-wraparound
unsigned char *pw = len ? malloc(len * 2) : strdup("");
CURLcode result;
if (!pw)
return CURLE_OUT_OF_MEMORY;
}
// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/
static int
defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
XML_Bool isId, const XML_Char *value, XML_Parser parser)
{
DEFAULT_ATTRIBUTE *temp;
int count = type->allocDefaultAtts * 2;
// ruleid: raptor-integer-wraparound
temp = (DEFAULT_ATTRIBUTE *)realloc(type->defaultAtts,
(count * sizeof(DEFAULT_ATTRIBUTE)));
if (temp == NULL)
return 0;
type->allocDefaultAtts = count;
type->defaultAtts = temp;
}
// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/
static enum XML_Error
doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
int tok, const char *next, const char **nextPtr, XML_Bool haveMore,
XML_Bool allowClosingDoctype, enum XML_Account account)
{
case XML_ROLE_GROUP_OPEN:
if (parser->m_prologState.level >= parser->m_groupSize)
{
if (parser->m_groupSize)
{
// ruleid: raptor-integer-wraparound
char *const new_connector = (char *)realloc(
parser->m_groupConnector, parser->m_groupSize *= 2);
}
}
// ...
return XML_ERROR_NONE;
}
// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/
int test_propagation()
{
lVar2 = sVar1 * 2;
// ruleid: raptor-integer-wraparound
data = (void *)(*(code *)malloc)(lVar2);
// ...
return 0;
}
// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/
int more_operands()
{
// ruleid: raptor-integer-wraparound
__s = (char *)(*(code *)malloc)(sVar7 * 3 + 1);
// ...
return 0;
}
// https://cc-sw.com/using-codeql-and-semgrep-to-assist-vulnerability-research-part-1-of-6/
int printbuf_memappend(printbuf *p, char *buf, int size)
{
if (p->size <= iVar2)
{
iVar3 = p->size * 2; // Integer overflow
if (iVar3 <= iVar2 + 8)
{
iVar3 = iVar2 + 9;
}
// ruleid: raptor-integer-wraparound
__ptr = (char *)realloc(__ptr, (long)iVar3); // Alloc call
}
}
#include <windows.h>
#include <iostream>
int windows_example()
{
int nresp = 1073741824; // 2^30, close to INT_MAX
size_t size = nresp * sizeof(char *); // Overflow occurs here!
// If sizeof(char*) == 4, then nresp * 4 = 4,294,967,296
// But this exceeds UINT32_MAX (4,294,967,295), so it wraps to 0
if (size == 0)
{
std::cerr << "Integer overflow detected! Size is 0." << std::endl;
return 1;
}
// ruleid: raptor-integer-wraparound
LPVOID ptr = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (ptr == NULL)
{
std::cerr << "VirtualAlloc failed. Size may be invalid due to overflow." << std::endl;
return 1;
}
std::cout << "Memory allocated successfully at: " << ptr << std::endl;
VirtualFree(ptr, 0, MEM_RELEASE);
return 0;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,214 @@
rules:
- id: raptor-integer-wraparound
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: HIGH
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-190: Integer Overflow or Wraparound"
- "CWE-128: Wrap-around Error"
- "CWE-131: Incorrect Calculation of Buffer Size"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
- http://www.phrack.org/issues/60/10.html#article
- https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples
- https://dustri.org/b/playing-with-weggli.html
message: >-
The software performs a calculation that can produce an integer
overflow or wraparound, when the logic assumes that the resulting
value will always be larger than the original value. This can
introduce other weaknesses when the calculation is used for resource
management or execution control.
severity: WARNING
languages:
- c
- cpp
# NOTE: only multiplication and sum with two operands are covered; other arithmetic operations should also be considered (e.g., left shift, even subtraction), as well as any operation with more than two operands.
# NOTE: some allocation functions such as `kmalloc`, `HeapAlloc`, and custom wrappers are not covered.
# NOTE: there might exist other buggy input validation patterns not covered here, including the same patterns with a different order of operands.
# NOTE: consider excluding `strlen` patterns to avoid false positives (at the cost of some false negatives).
# NOTE: we should do some tests with the deep expression operator, refer also to `cpp.lang.security.memory.integer-overflow-allocation.integer-overflow-allocation`.
# NOTE: a dedicated rule for C++ operators such as `new` should be implemented.
pattern-either:
# malloc, valloc (multiplication)
- patterns:
- pattern-either:
- pattern: $FUN($_ * $_)
- pattern: $FUN($_ *= $_)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: malloc
- pattern: valloc
- patterns:
- pattern: $FUN($N)
- pattern-either:
- pattern-inside: |
$N = $_ * $_;
...
- pattern-inside: |
$N *= $_;
...
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: malloc
- pattern: valloc
# malloc, valloc (sum)
- patterns:
- pattern-either:
- pattern: $FUN($_ + $_)
- pattern: $FUN($_ += $_)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: malloc
- pattern: valloc
- patterns:
- pattern: $FUN($N)
- pattern-either:
- pattern-inside: |
$N = $_ + $_;
...
- pattern-inside: |
$N += $_;
...
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: malloc
- pattern: valloc
# calloc, realloc, reallocf, aligned_alloc, VirtualAlloc (multiplication)
- patterns:
- pattern-either:
- pattern: $FUN($_, $_ * $_, ...)
- pattern: $FUN($_, $_ *= $_, ...)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: calloc
- pattern: realloc
- pattern: reallocf
- pattern: aligned_alloc
- pattern: VirtualAlloc
- patterns:
- pattern: $FUN($_, $N, ...)
- pattern-either:
- pattern-inside: |
$N = $_ * $_;
...
- pattern-inside: |
$N *= $_;
...
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: calloc
- pattern: realloc
- pattern: reallocf
- pattern: aligned_alloc
- pattern: VirtualAlloc
# calloc, realloc, reallocf, aligned_alloc, VirtualAlloc (sum)
- patterns:
- pattern-either:
- pattern: $FUN($_, $_ + $_, ...)
- pattern: $FUN($_, $_ += $_, ...)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: calloc
- pattern: realloc
- pattern: reallocf
- pattern: aligned_alloc
- pattern: VirtualAlloc
- patterns:
- pattern: $FUN($_, $N, ...)
- pattern-either:
- pattern-inside: |
$N = $_ + $_;
...
- pattern-inside: |
$N += $_;
...
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: calloc
- pattern: realloc
- pattern: reallocf
- pattern: aligned_alloc
- pattern: VirtualAlloc
# calloc (multiplication in 1st arg)
- patterns:
- pattern-either:
- pattern: $FUN($_ * $_, $_)
- pattern: $FUN($_ *= $_, $_)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: calloc
- patterns:
- pattern: $FUN($N, $_)
- pattern-either:
- pattern-inside: |
$N = $_ * $_;
...
- pattern-inside: |
$N *= $_;
...
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: calloc
# calloc (sum in 1st arg)
- patterns:
- pattern-either:
- pattern: $FUN($_ + $_, $_)
- pattern: $FUN($_ += $_, $_)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: calloc
- patterns:
- pattern: $FUN($N, $_)
- pattern-either:
- pattern-inside: |
$N = $_ + $_;
...
- pattern-inside: |
$N += $_;
...
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: calloc
# buggy input validation (sum)
# consider integer promotion (i.e., uint16_t are not vulnerable on 32-bit systems)
- pattern: $X > $MAX || ($X + $_) > $MAX
- pattern: $X >= $MAX || ($X + $_) > $MAX
- pattern: $X > $MAX || ($X + $_) >= $MAX
- pattern: $X >= $MAX || ($X + $_) >= $MAX
- pattern: $X < $MAX && ($X + $_) < $MAX
- pattern: $X <= $MAX && ($X + $_) < $MAX
- pattern: $X < $MAX && ($X + $_) <= $MAX
- pattern: $X <= $MAX && ($X + $_) <= $MAX
# buggy input validation (multiplication)
# consider integer promotion (i.e., uint16_t are not vulnerable on 32-bit systems)
- pattern: $X > $MAX || ($X * $_) > $MAX
- pattern: $X >= $MAX || ($X * $_) > $MAX
- pattern: $X > $MAX || ($X * $_) >= $MAX
- pattern: $X >= $MAX || ($X * $_) >= $MAX
- pattern: $X < $MAX && ($X * $_) < $MAX
- pattern: $X <= $MAX && ($X * $_) < $MAX
- pattern: $X < $MAX && ($X * $_) <= $MAX
- pattern: $X <= $MAX && ($X * $_) <= $MAX
@@ -0,0 +1,340 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define BUFSIZE 256
void drop_priv_perm()
{
// ruleid: raptor-interesting-api-calls
setuid(getuid());
}
void drop_priv_temp()
{
// ruleid: raptor-interesting-api-calls
seteuid(getuid());
}
void copy_append_string(char *string1, char *string2)
{
char buf[BUFSIZE];
// ruleid: raptor-interesting-api-calls
strcpy(buf, string1);
// ruleid: raptor-interesting-api-calls
strcat(buf, string2);
}
void copy_string(char *string)
{
char buf[BUFSIZE];
// ruleid: raptor-interesting-api-calls
stpcpy(buf, string);
}
void copy_string1(char *string)
{
char buf[BUFSIZE];
// ruleid: raptor-interesting-api-calls
strncpy(buf, string, BUFSIZE);
}
void copy_string2(char *string)
{
char buf[BUFSIZE];
// ruleid: raptor-interesting-api-calls
stpncpy(buf, string, BUFSIZE);
}
void get_string()
{
char buf[BUFSIZE];
// ruleid: raptor-interesting-api-calls
gets(buf);
}
void memory_copy()
{
// ...
// ruleid: raptor-interesting-api-calls
memcpy(&(((char *)p_buf)[serialization_buffer_offset]),
serialized_context_buffer,
serialized_context_size);
// ...
// ruleid: raptor-interesting-api-calls
memcpy(&(((char *)p_buf)[serialization_buffer_offset]),
serialized_profiles_context_buffer,
cfl_sds_len(serialized_profiles_context_buffer));
// ...
// ruleid: raptor-interesting-api-calls
memcpy((void *)str->wrapped.buf, src, 3 * length + 1);
// ...
if (net_setup == NULL)
{
flb_net_setup_init(&stream->net);
}
else
{
// ok: raptor-interesting-api-calls
memcpy(&stream->net, net_setup, sizeof(struct flb_net_setup));
}
// ...
crc = __bswap_32(crc32(0, (const Bytef *)data, len));
// ok: raptor-interesting-api-calls
memcpy((char *)c->block_data + outlen, &crc, 4);
c->used_size = outlen + 4;
// ...
// ok: raptor-interesting-api-calls
memcpy(&load_command, pcmd, sizeof load_command);
// ...
// chose not to use pattern-not: $FUN($_, $_, <... sizeof(...) ...>, ...)
// ruleid: raptor-interesting-api-calls
memcpy(temp, sysconfig->sortlist,
sizeof(*channel->sortlist) * sysconfig->nsortlist);
}
// https://cc-sw.com/semgrep-guide-for-a-security-engineer-part-6-of-6/
static int service_attr_req(sdp_req_t *req, sdp_buf_t *buf)
{
sdp_cont_state_t *cstate = NULL;
// ...
if (cstate)
{
sdp_buf_t *pCache = sdp_get_cached_rsp(cstate);
SDPDBG("Obtained cached rsp : %p", pCache);
if (pCache)
{
short sent = MIN(max_rsp_size, pCache->data_size - cstate->cStateValue.maxBytesSent);
pResponse = pCache->data;
// ruleid: raptor-interesting-api-calls
memcpy(buf->data, pResponse + cstate->cStateValue.maxBytesSent, sent); // Out-of-bound read here
buf->data_size += sent;
cstate->cStateValue.maxBytesSent += sent;
// ...
}
// ...
}
}
static int call_clone3(uint64_t flags, size_t size, enum test_mode test_mode)
{
struct __clone_args args = {
.flags = flags,
.exit_signal = SIGCHLD,
};
struct clone_args_extended
{
struct __clone_args args;
__aligned_u64 excess_space[2];
} args_ext;
pid_t pid = -1;
int status;
memset(&args_ext, 0, sizeof(args_ext));
if (size > sizeof(struct __clone_args))
args_ext.excess_space[1] = 1;
if (size == 0)
size = sizeof(struct __clone_args);
switch (test_mode)
{
case CLONE3_ARGS_NO_TEST:
/*
* Uses default 'flags' and 'SIGCHLD'
* assignment.
*/
break;
case CLONE3_ARGS_ALL_0:
args.flags = 0;
args.exit_signal = 0;
break;
case CLONE3_ARGS_INVAL_EXIT_SIGNAL_BIG:
args.exit_signal = 0xbadc0ded00000000ULL;
break;
case CLONE3_ARGS_INVAL_EXIT_SIGNAL_NEG:
args.exit_signal = 0x0000000080000000ULL;
break;
case CLONE3_ARGS_INVAL_EXIT_SIGNAL_CSIG:
args.exit_signal = 0x0000000000000100ULL;
break;
case CLONE3_ARGS_INVAL_EXIT_SIGNAL_NSIG:
args.exit_signal = 0x00000000000000f0ULL;
break;
}
memcpy(&args_ext.args, &args, sizeof(struct __clone_args));
// currently commented-out in the rule to avoid too much noise
// todoruleid: raptor-interesting-api-calls
pid = sys_clone3((struct __clone_args *)&args_ext, size);
if (pid < 0)
{
ksft_print_msg("%s - Failed to create new process\n",
strerror(errno));
return -errno;
}
if (pid == 0)
{
ksft_print_msg("I am the child, my PID is %d\n", getpid());
_exit(EXIT_SUCCESS);
}
ksft_print_msg("I am the parent (%d). My child's pid is %d\n",
getpid(), pid);
if (waitpid(-1, &status, __WALL) < 0)
{
ksft_print_msg("Child returned %s\n", strerror(errno));
return -errno;
}
if (WEXITSTATUS(status))
return WEXITSTATUS(status);
return 0;
}
static pid_t sys_clone3(struct clone_args *args)
{
// ruleid: raptor-interesting-api-calls
return syscall(__NR_clone3, args, sizeof(struct clone_args));
}
int test_exec(void)
{
// ok: raptor-interesting-api-calls
void *system_wide = system_path(ETC_GITATTRIBUTES);
printf("Main program started\n");
char *argv[] = {"jim", "jams", NULL};
char *envp[] = {"some", "environment", NULL};
// ruleid: raptor-interesting-api-calls
if (execve("./sub", argv, envp) == -1)
perror("Could not execve");
// ruleid: raptor-interesting-api-calls
execlp(path, "emacsclient", "-e", man_page.buf, (char *)NULL);
// ruleid: raptor-interesting-api-calls
execl(SHELL_PATH, SHELL_PATH, "-c", shell_cmd.buf, (char *)NULL);
// ruleid: raptor-interesting-api-calls
execv(user_argv[0], (char *const *)user_argv);
// ruleid: raptor-interesting-api-calls
return system("echo 3 | sudo tee /proc/sys/vm/drop_caches");
return 1;
}
void test_spawn(int argc, char *argv[])
{
pid_t child;
int fd_count, fd_map[10];
struct inheritance inherit;
const char *c_argv[10], *c_envp[10];
char buf[256];
int nbytes;
int c_stdin[2], c_stdout[2], c_stderr[2]; /* Pipes for child
* communication */
/* Create pipes to communicate with child via stdin/stdout/stderr */
// ruleid: raptor-interesting-api-calls
if (pipe(c_stdin) || pipe(c_stdout) || pipe(c_stderr))
{
perror("Bad pipe");
exit(-1);
}
/* Set up file descriptor map for child process */
fd_map[0] = dup(c_stdin[0]); /* child stdin is read end of pipe */
fd_map[1] = dup(c_stdout[1]); /* child stdout is write end of pipe */
fd_map[2] = dup(c_stderr[1]); /* child stderr is write end of pipe */
fd_count = 3;
/* Close unused end of pipes for the parent */
close(c_stdin[0]);
close(c_stdout[1]);
close(c_stderr[1]);
/* Build the argument structure for child arguments.
* [0] is the program name */
c_argv[0] = "spawnc";
c_argv[1] = "arg1";
c_argv[2] = "arg2";
c_argv[3] = NULL;
/* Build the environment structure which defines the child's
* environment variables */
c_envp[0] = "TEST_ENV=YES";
c_envp[1] = "BPX_SHAREAS=NO";
c_envp[2] = NULL;
/* Spawn the child process */
// ruleid: raptor-interesting-api-calls
child = spawnp("spawnc", fd_count, fd_map, &inherit, c_argv, c_envp);
// ruleid: raptor-interesting-api-calls
child = spawn("/usr/bin/spawnc", fd_count, fd_map, &inherit, c_argv, c_envp);
if (child == -1)
{
perror("Error on spawn");
exit(-1);
}
else
printf("Spawned %i\n", child);
/* Test interaction with the child process */
printf("parent: Asking child, \"what are you doing?\\n\"\n");
// ruleid: raptor-interesting-api-calls
strcpy(buf, "child from parent: what are you doing?\n");
if (write(c_stdin[1], buf, sizeof(buf)) == -1)
{
perror("write stdout");
exit(-1);
}
memset(buf, 0, 255); /* Just zeroing out the buffer */
printf("parent: reading from child now\n");
// ruleid: raptor-interesting-api-calls
if ((nbytes = read(c_stdout[0], buf, 255)) == -1)
{
perror("read error:");
exit(-1);
}
printf("parent: child says, \"%s\"\n", buf);
/* Cleanup pipes before exiting */
close(c_stdin[1]);
close(c_stdout[0]);
close(c_stderr[0]);
exit(0);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,263 @@
rules:
- id: raptor-interesting-api-calls
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Dangerous Method or Function
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-676: Use of Potentially Dangerous Function"
owasp:
- A08:2025 - Software or Data Integrity Failures
references:
- https://github.com/0xdea/rhabdomancer
- https://github.com/0xdea/ghidra-scripts/blob/main/Rhabdomancer.java
- https://github.com/x509cert/banned/blob/master/banned.h
- https://g.co/kgs/PCHQjJ
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
- https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/28719-banned-api-usage-use-updated-function-replacement
- https://docs.oracle.com/cd/E37838_01/html/E61050/gnclc.html
message: >-
Locate all calls to interesting and potentially insecure API
functions (candidate points). The auditor can backtrace from these
candidate points to find pathways allowing access from untrusted
input.
severity: WARNING
languages:
- c
- cpp
# NOTE: `goto`, `try/catch`, `sem/mutex`, `new/delete`, and `static_cast/reinterpret_cast` are not covered.
# NOTE: not all Microsoft-specific obsolete functions are covered.
# NOTE: consider excluding some matches for `strncpy`, `snprintf`, and similar functions where the length parameter is known at compile time (see `memcpy` below for an example). See also another possible approach described at https://cc-sw.com/semgrep-guide-for-a-security-engineer-part-6-of-6/. Beware of possible false negatives, though.
# NOTE: consider checking for format string specifiers that match the `(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)` regex.
# NOTE: consider extracting some patterns into separate rules to focus on the most interesting API calls (copy operations, exec functions, etc.).
# NOTE: nonlocking stdio functions (https://linux.die.net/man/3/fgets_unlocked) are not covered.
# NOTE: refer also to https://semgrep.dev/r?lang=C
pattern-either:
# priv
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*set\w*(u|g)id\s*$|^\w*(init|set)groups\s*$|^\w*Impersonate\w*\s*$'
# strcpy
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*str\w?(cpy|add)(_s)?(_l)?\s*$|^\w*stpn?cpy(_s)?(_l)?\s*$|^\w*(wc|mb|ftc|tc)s\w?cpy(_s)?(_l)?\s*$|^\w*wcpn?cpy(_s)?(_l)?\s*$'
# strcat
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*str\w?cat(_s)?(_l)?\s*$|^\w*(wc|mb|ftc|tc)s\w?cat(_s)?(_l)?\s*$'
# strtok
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*strtok(_r)?(_s)?(_l)?\s*$|^\w*(wc|mb)stok(_r)?(_s)?(_l)?\s*$|^\w*str(find|rspn|trns)\s*$'
# more string parsing (too noisy?)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*strr?chr\s*$|^\w*memchr\s*$|^\w*str(str|sep)\s*$|^\w*strc?spn\s*$|^\w*(str|wcs)pbrk\s*$'
# strlen (too noisy)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*(str|wcs|mbs)n?len\s*$'
# printf
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*s\w*printf(_s)?(_l)?\w*\s*$'
# more printf (should be covered by the format-string-bugs rule)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*printf\w*\s*$|^\w*err\w*\s*$|^\w*warn\w*\s*$|^\w*syslog\w*\s*$'
# scanf
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*scanf(_s)?(_l)?\s*$'
# get
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*get(s|ws(_l)?|ts|tws|c|char|pw|pass|wd|cwd|login(_r)?|groups|hostname|domainname|opt|opt_long)\s*$|^\w*cuserid\s*$'
# environment
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*(get|set|put|unset)env\s*$|^\w*g_get_(home|tmp)_dir\s*$'
# memcpy
- patterns:
- pattern: $FUN($_, $_, $LEN, ...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*mem(c|p)?cpy(_s)?\s*$|^\w*memmove(_s)?\s*$|^\w*bcopy\s*$|^\w*CopyMemory\s*$'
# exclude length known at compile time (sizeof macro) - imperfect match with `memccpy`, but that's acceptable
- pattern-not: $FUN($_, $_, sizeof(...), ...)
# - pattern-not: $FUN($_, $_, <... sizeof(...) ...>, ...)
# exclude length known at compile time (numeric literal)
- metavariable-regex:
metavariable: $LEN
regex: '^(?!\s*(?:0[xX][0-9A-Fa-f]+|0[bB][01]+|0[0-7]*|[1-9][0-9]*)[uUlL]*\s*$).+'
# memset (too noisy, mostly irrelevant unless you use it to erase sensitive data)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*memset(_explicit)?\s*$|^\w*(explicit_)?bzero\s*$'
# alloc
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*alloc(a|f)?\s*$|^\w*alloc_?array\s*$'
# free (too noisy)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*free\s*$'
# exec
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*exec(l|v)?(p|e)?e?\s*$|^\w*system\s*$|^\w*spawn\w?\s*$|^\w*wordexp\s*$|^\w*WinExec\s*$|^\w*ShellExecute(A|ExA|W|ExW)?\s*$|^\w*CreateProcess(A|AsUserA|W|AsUserW|WithLogonW|WithTokenW)?\s*$'
# i/o
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*open(at)?(64)?\s*$|^\w*pipe\s*$|^\w*read\s*$|^\w*recv(from)?\s*$|^\w*copylist\s*$|^\w*dbminit\s*$|^\w*LoadLibrary(A|ExA|W|ExW)?\s*$'
# more i/o (too noisy)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*connect\s*$|^\w*write\s*$|^\w*hton(l|s)\s*$|^\w*ntoh(l|s)\s*$|^\w*dup2?\s*$'
# proc
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*fork\s*$'
# more proc (too noisy)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*clone3?\s*$'
# rand
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*rand(_r|48)?\s*$'
# tmp
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*mk\w?temp(64)?\s*$|^\w*te?mpnam(_r)?\s*$|^\w*tmpfile\s*$|^\w*GetTempFileName(A|W)?\s*$'
# file
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*(mk|ch)(dir|nod)(at)?\s*$|^\w*creat\s*$|^\w*link(at)?\s*$|^\w*rename(at)?\s*$|^\w*access(at|at2|_ok)?\s*$|^\w*stat(at)?\s*$|^\w*ch(own|mod|root)(at)?\s*$|^\w*realpath\s*$|^\w*readlink(at)?\s*$|^\w*(tty|pts)name_r\s*$'
# more file
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*locale\s*$|^\w*(make|split)path\s*$|^\w*fattach\s*$|^\w*ftw\s*$|^\w*truncate\s*$|^\w*u(mask|limit)\s*$|^\w*AddAccessAllowedAce\s*$'
# conf
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*confstr\s*$|^\w*utmpx?name\s*$'
# string conversions
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*mbs(nr|r)?towcs(_l)?\s*$|^\w*wcs(nr|r)?tombs(_l)?\s*$|^\w*OemToCharW\s*$|^\w*MultiByteToWideChar\s*$'
# character conversions (mostly irrelevant)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*mbr?towc(_l)?\s*$|^\w*wcr?tomb(_l)?\s*$'
# inet
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*inet_(ntop|pton)\s*$'
# signals (too noisy)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*kill\s*$|^\w*signal\s*$|^\w*sigaction\s*$|^\w*(set|long)jmp\s*$'
# time
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*cftime\s*$'
# syscall
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*syscall\s*$'
# kernel
- patterns:
- pattern: $FUN(...)
- metavariable-regex:
metavariable: $FUN
regex: '(?i)^\w*copy_(from|to)_user\s*$|^\w*(get|put)_user\s*$|^\w*copy(in|out)\s*$|^\w*cdev_init\s*$'
# more kernel (too noisy)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*ioctl\w*\s*$|^\w*m(re|un)?map\s*$'
# more kernel (too noisy)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*cpu_to_(b|l)e(16|32|64)(p|s)?\s*$|^\w*(b|l)e(16|32|64)(p|s)?_to_cpu\s*$|^\w*xb_get_(32|64|bytes|word_array|bitmap)\s*$'
# assert (should be covered by suspicious-assert rule)
# - patterns:
# - pattern: $FUN(...)
# - metavariable-regex:
# metavariable: $FUN
# regex: '(?i)^\w*assert\w*\s*$'
# switch (too noisy)
# - pattern: |
# switch ($VAR) { }
@@ -0,0 +1,51 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#define BUFSIZE 256
#define FMT "whatever"
void print_address(char *string)
{
char buf[BUFSIZE];
char fmt[] = "whatever";
// ruleid: raptor-memory-address-exposure
printf("address: %p\n", buf);
// ruleid: raptor-memory-address-exposure
sprintf(buf, "address: %x\n", string);
// ok: raptor-memory-address-exposure
sprintf(buf, FMT, string);
// ok: raptor-memory-address-exposure
sprintf(buf, fmt, string);
// ok: raptor-memory-address-exposure
sprintf(buf, string);
}
char *genUniqueVal(Node *n)
{
char *buf = (char *)malloc(32);
if (!buf)
return NULL;
memset(buf, 0x0, 32);
uint32_t uval = &buf;
if (uval == 0)
{
uval = drand();
}
// ruleid: raptor-memory-address-exposure
snprintf(buf, 32, "%x", uval);
return buf;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,77 @@
rules:
- id: raptor-memory-address-exposure
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Mishandled Sensitive Information
likelihood: LOW
impact: MEDIUM
confidence: LOW
technology:
- c
- cpp
cwe:
- "CWE-209: Generation of Error Message Containing Sensitive Information"
- "CWE-497: Exposure of Sensitive System Information to an Unauthorized Control Sphere"
owasp:
- A04:2025 - Cryptographic Failures
references:
- https://github.com/struct/mms
message: >-
The software generates an error message that includes sensitive
information about its environment, users, or associated data.
In particular, exposure of memory addresses might defeat ASLR.
severity: INFO
languages:
- c
- cpp
# NOTE: `#define` format specifiers are not considered due to Semgrep limitations, perhaps we could implement this with symbolic propagation (Semgrep Pro experimental feature)?
patterns:
- pattern-either:
# format string in 1st arg
- pattern: printf($FMT, ...)
- pattern: vprintf($FMT, ...)
- pattern: wprintf($FMT, ...)
- pattern: vwprintf($FMT, ...)
- pattern: vcprintf($FMT, ...)
- pattern: vcwprintf($FMT, ...)
- pattern: vscprintf($FMT, ...)
- pattern: vscwprintf($FMT, ...)
- pattern: printk($FMT, ...)
- pattern: warn($FMT, ...)
- pattern: vwarn($FMT, ...)
- pattern: warnx($FMT, ...)
- pattern: vwarnx($FMT, ...)
# format string in 2nd arg
- pattern: fprintf($_, $FMT, ...)
- pattern: vfprintf($_, $FMT, ...)
- pattern: fwprintf($_, $FMT, ...)
- pattern: vfwprintf($_, $FMT, ...)
- pattern: sprintf($_, $FMT, ...)
- pattern: vsprintf($_, $FMT, ...)
- pattern: asprintf($_, $FMT, ...)
- pattern: vasprintf($_, $FMT, ...)
- pattern: dprintf($_, $FMT, ...)
- pattern: vdprintf($_, $FMT, ...)
- pattern: wsprintf($_, $FMT, ...)
- pattern: syslog($_, $FMT, ...)
- pattern: vsyslog($_, $FMT, ...)
- pattern: err($_, $FMT, ...)
- pattern: verr($_, $FMT, ...)
- pattern: errx($_, $FMT, ...)
- pattern: verrx($_, $FMT, ...)
- pattern: warnc($_, $FMT, ...)
- pattern: vwarnc($_, $FMT, ...)
# format string in 3rd arg
- pattern: snprintf($_, $_, $FMT, ...)
- pattern: vsnprintf($_, $_, $FMT, ...)
- pattern: swprintf($_, $_, $FMT, ...)
- pattern: vswprintf($_, $_, $FMT, ...)
- pattern: errc($_, $_, $FMT, ...)
- pattern: verrc($_, $_, $FMT, ...)
- metavariable-regex:
metavariable: $FMT
# NOTE: some format string specifiers are not handled
regex: '(".*%\w*x.*"|".*%\w*X.*"|".*%\w*p.*")'
@@ -0,0 +1,81 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
void bad1()
{
BarObj *ptr = new BarObj()
// ruleid: raptor-mismatched-memory-management-cpp
free(ptr);
}
void good1()
{
BarObj *ptr = new BarObj()
// ok: raptor-mismatched-memory-management-cpp
delete ptr;
}
class A
{
void bad2();
void good2();
};
void A::bad2()
{
int *ptr;
ptr = (int *)malloc(sizeof(int));
// ruleid: raptor-mismatched-memory-management-cpp
delete ptr;
}
void A::good2()
{
int *ptr;
ptr = (int *)malloc(sizeof(int));
// ok: raptor-mismatched-memory-management-cpp
free(ptr);
}
class B
{
void bad3(bool);
void good3();
};
void B::bad3(bool heap)
{
int localArray[2] = {11, 22};
int *p = localArray;
if (heap)
{
p = new int[2];
}
// ruleid: raptor-mismatched-memory-management-cpp
delete[] p;
}
void B::good3()
{
int localArray[2] = {11, 22};
int *p = localArray;
p = new (std::nothrow) int[2];
// ok: raptor-mismatched-memory-management-cpp
delete[] p;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,67 @@
rules:
- id: raptor-mismatched-memory-management-cpp
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: LOW
impact: MEDIUM
confidence: LOW
technology:
- cpp
cwe:
- "CWE-762: Mismatched Memory Management Routines"
owasp:
- A06:2025 - Insecure Design
references:
- https://github.com/struct/mms
- https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples
message: >-
The software attempts to return a memory resource to the system, but
it calls a release function that is not compatible with the function
that was originally used to allocate that resource.
Due to inherent limitations of Semgrep, this rule might generate many
false positives and should therefore be customized for your codebase.
severity: INFO
languages:
- cpp
# NOTE: `valloc`, `reallocf`, `aligned_alloc`, and custom wrappers are not covered.
# NOTE: overloaded operators, `VirtualAlloc/VirtualFree`, and `mmap/munmap` are not covered.
pattern-either:
# free
- patterns:
- pattern: free($PTR)
- pattern-not-inside: |
$PTR = malloc(...);
...
- pattern-not-inside: |
$PTR = calloc(...);
...
- pattern-not-inside: |
$PTR = realloc(...);
...
- pattern-not-inside: |
$PTR = strdup(...);
...
- pattern-not-inside: |
$PTR = strndup(...);
...
# delete[]
- patterns:
- pattern: delete[]($PTR)
- pattern-not-inside: |
$PTR = new $_[$_];
...
# delete
- patterns:
- pattern: delete($PTR)
- pattern-not-inside: |
$PTR = new $_;
...
- patterns:
- pattern: delete($PTR)
- pattern-inside: |
$PTR = new $_[$_];
...
@@ -0,0 +1,28 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
void bad1()
{
int localArray[2] = {11, 22};
int *p = localArray;
// ruleid: raptor-mismatched-memory-management
free(p);
}
void good1()
{
int *ptr;
ptr = (int *)malloc(sizeof(int));
// ok: raptor-mismatched-memory-management
free(ptr);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,51 @@
rules:
- id: raptor-mismatched-memory-management
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: LOW
impact: MEDIUM
confidence: LOW
technology:
- c
- cpp
cwe:
- "CWE-762: Mismatched Memory Management Routines"
owasp:
- A06:2025 - Insecure Design
references:
- https://github.com/struct/mms
message: >-
The software attempts to return a memory resource to the system, but
it calls a release function that is not compatible with the function
that was originally used to allocate that resource.
Due to inherent limitations of Semgrep, this rule might generate many
false positives and should therefore be customized for your codebase.
severity: INFO
languages:
- c
- cpp
# NOTE: `valloc`, `reallocf`, `aligned_alloc`, and custom wrappers are not covered.
# NOTE: `VirtualAlloc/VirtualFree` and `mmap/munmap` are not covered.
pattern-either:
# free
- patterns:
- pattern: free($PTR)
- pattern-not-inside: |
$PTR = malloc(...);
...
- pattern-not-inside: |
$PTR = calloc(...);
...
- pattern-not-inside: |
$PTR = realloc(...);
...
- pattern-not-inside: |
$PTR = strdup(...);
...
- pattern-not-inside: |
$PTR = strndup(...);
...
@@ -0,0 +1,141 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define FAIL 0
#define PASS 1
void bad1(char *data)
{
int result = security_check(data);
// ruleid: raptor-missing-break-in-switch
switch (result)
{
case FAIL:
printf("Security check failed!\n");
case PASS:
printf("Security check passed.\n");
break;
default:
printf("Unknown error (%d), exiting...\n", result);
exit(1);
}
}
void good1(char *data)
{
int result = security_check(data);
// ok: raptor-missing-break-in-switch
switch (result)
{
case FAIL:
printf("Security check failed!\n");
exit(1);
case PASS:
printf("Security check passed.\n");
break;
default:
printf("Unknown error (%d), exiting...\n", result);
exit(1);
}
}
struct object *init_object(int type)
{
struct object *obj;
if (!(obj = (struct object *)malloc(sizeof(struct object))))
return NULL;
obj->type = type;
// ruleid: raptor-missing-break-in-switch
switch (type)
{
case OBJ_STR:
obj->un.str = alloc_string();
case OBJ_INT:
obj->un.num = alloc_int();
break;
case OBJ_BOOL:
obj->un.bool = alloc_bool();
break;
}
return obj;
}
void printMessage(int month)
{
// ruleid: raptor-missing-break-in-switch
switch (month)
{
case 1:
printf("January");
case 2:
printf("February");
case 3:
printf("March");
case 4:
printf("April");
case 5:
printff("May");
case 6:
printf("June");
case 7:
printf("July");
case 8:
printf("August");
case 9:
printf("September");
case 10:
printf("October");
case 11:
printf("November");
case 12:
printf("December");
}
printf(" is a great month");
}
char *escape_string(char *string)
{
char *output, *dest;
int escape = 0;
// there's also an incorrect use of sizeof() here
if (!(output = dest = (char *)calloc(strlen(string + 1, sizeof(string)))))
die("calloc: %m");
while (*string)
{
// ruleid: raptor-missing-break-in-switch
switch (*cp)
{
case '\\':
if (escape)
{
*dest++ = '\\';
escape = 0;
}
else
escape = 1;
break;
case '\n':
*dest++ = ' ';
default:
*string = *dest++;
}
string++;
}
return output;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,66 @@
rules:
- id: raptor-missing-break-in-switch
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Other Security
likelihood: LOW
impact: LOW
confidence: LOW
technology:
- c
- cpp
cwe:
- "CWE-484: Omitted Break Statement in Switch"
owasp:
- A08:2025 - Software or Data Integrity Failures
references:
- https://g.co/kgs/PCHQjJ
- https://github.com/struct/mms
- https://github.com/returntocorp/semgrep/issues/4939
message: >-
The software omits a break statement within a switch or similar
construct, causing code associated with multiple conditions to
execute. This can cause problems when the programmer only intended to
execute code associated with one condition.
severity: INFO
languages:
- c
- cpp
# NOTE: we should also check for default blocks that miss the `break/return/exit/goto` or equivalent statement/function call.
patterns:
- pattern: |
switch ($VAR) { case $VAL1: ... case $VAL2: ... }
# break
- pattern-not: |
switch ($VAR) { case $VAL1: ... break; case $VAL2: ... }
- pattern-not: |
switch ($VAR) { case $VAL1: break; case $VAL2: ... }
# exit
- pattern-not: |
switch ($VAR) { case $VAL1: ... exit($_); case $VAL2: ... }
- pattern-not: |
switch ($VAR) { case $VAL1: exit($_); case $VAL2: ... }
# return
- pattern-not: |
switch ($VAR) { case $VAL1: ... return; case $VAL2: ... }
- pattern-not: |
switch ($VAR) { case $VAL1: return; case $VAL2: ... }
- pattern-not: |
switch ($VAR) { case $VAL1: ... return $_; case $VAL2: ... }
- pattern-not: |
switch ($VAR) { case $VAL1: return $_; case $VAL2: ... }
# goto
- pattern-not: |
switch ($VAR) { case $VAL1: ... goto $_; case $VAL2: ... }
- pattern-not: |
switch ($VAR) { case $VAL1: goto $_; case $VAL2: ... }
# throw (C++)
# - pattern-not: |
# switch ($VAR) { case $VAL1: ... throw $_; case $VAL2: ... }
# - pattern-not: |
# switch ($VAR) { case $VAL1: throw $_; case $VAL2: ... }
# improve output readability
- focus-metavariable: $VAR
@@ -0,0 +1,128 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define FAIL 0
#define PASS 1
void bad1(char *data)
{
int result = security_check(data);
// ruleid: raptor-missing-default-in-switch
switch (result)
{
case FAIL:
printf("Security check failed!\n");
exit(1);
break;
case PASS:
printf("Security check passed.\n");
break;
}
}
void good1(char *data)
{
int result = security_check(data);
// ok: raptor-missing-default-in-switch
switch (result)
{
case FAIL:
printf("Security check failed!\n");
exit(1);
break;
case PASS:
printf("Security check passed.\n");
break;
default:
printf("Unknown error (%d), exiting...\n", result);
exit(1);
}
}
void bad2(Pkt packet)
{
// ruleid: raptor-missing-default-in-switch
switch (packet->id)
{
case 1:
initAuth(packet);
break;
case 2:
initReset(packet);
break;
case 3:
initDisconnect(packet);
break;
}
processPacket(packet);
}
struct object *init_object(int type)
{
struct object *obj;
if (!(obj = (struct object *)malloc(sizeof(struct object))))
return NULL;
obj->type = type;
// ruleid: raptor-missing-default-in-switch
switch (type)
{
case OBJ_STR:
obj->un.str = alloc_string();
break;
case OBJ_INT:
obj->un.num = alloc_int();
break;
case OBJ_BOOL:
obj->un.bool = alloc_bool();
break;
}
return obj;
}
void test()
{
// ruleid: raptor-missing-default-in-switch
switch (foo() + x + y)
{
case 1:
break;
case 2:
break;
}
// ok: raptor-missing-default-in-switch
switch (foo() + x + y)
{
case 1:
break;
default:
break;
case 2:
break;
}
// ok: raptor-missing-default-in-switch
switch (foo() + x + y)
{
case 1:
break;
case 2:
break;
default:
break;
}
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,36 @@
rules:
- id: raptor-missing-default-in-switch
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Other Security
likelihood: LOW
impact: LOW
confidence: LOW
technology:
- c
- cpp
cwe:
- "CWE-478: Missing Default Case in Multiple Condition Expression"
owasp:
- A08:2025 - Software or Data Integrity Failures
references:
- https://g.co/kgs/PCHQjJ
- https://github.com/struct/mms
- https://github.com/returntocorp/semgrep/issues/4939
message: >-
The code does not have a default case in an expression with multiple
conditions, such as a switch statement.
severity: INFO
languages:
- c
- cpp
patterns:
- pattern: |
switch ($VAR) { }
- pattern-not: |
switch ($VAR) { default: ... }
# improve output readability
- focus-metavariable: $VAR
@@ -0,0 +1,28 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
// ok: raptor-missing-return
int bad();
// ok: raptor-missing-return
int baddie(int foo);
// ruleid: raptor-missing-return
int bad1(void)
{
printf("Hello, World!");
}
// ok: raptor-missing-return
void good1(void)
{
printf("Hello, World!");
}
// ok: raptor-missing-return
int main(int argc, char **argv)
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,43 @@
rules:
- id: raptor-missing-return
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Other Security
likelihood: LOW
impact: LOW
confidence: LOW
technology:
- c
- cpp
cwe:
- "CWE-393: Return of Wrong Status Code"
- "CWE-394: Unexpected Status Code or Return Value"
owasp:
- A08:2025 - Software or Data Integrity Failures
references:
- https://stackoverflow.com/questions/10858391/why-do-programs-in-c-compile-even-when-the-return-statement-is-missing
message: >-
A non-void function does not have a return statement. Hence, its
return value can be considered undefined.
severity: INFO
languages:
- c
- cpp
# NOTE: C++ class declarations should also be excluded, but apparently this pattern is not supported by Semgrep.
patterns:
- pattern: $_ $FUN(...) { ... }
# exclude function declarations
- pattern-not: $_ $FUN(...);
# exclude functions with return statement
- pattern-not: $_ $FUN(...) { ... return $_; }
# exclude main function
- pattern-not: int main(...) { ... }
# exclude void functions
- pattern-not: void $FUN(...) { ... }
# improve output readability
- focus-metavariable: $FUN
# exclude else if (commented-out for performance reasons)
# - pattern-not: ... if ($COND) { ... }
@@ -0,0 +1,390 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define BUFSIZE 256
void bad1(char *string)
{
char buf[BUFSIZE];
strncpy(buf, string, BUFSIZE);
// ruleid: raptor-off-by-one
buf[BUFSIZE] = '\0';
}
void good1(char *string)
{
char buf[BUFSIZE];
strncpy(buf, string, BUFSIZE);
// ok: raptor-off-by-one
buf[BUFSIZE - 1] = '\0';
}
void bad2(char *string)
{
char firstname[20];
char lastname[20];
char fullname[40];
fullname[0] = '\0';
// ruleid: raptor-off-by-one
strncat(fullname, firstname, 40);
}
void good2(char *string)
{
char firstname[20];
char lastname[20];
char fullname[40];
fullname[0] = '\0';
// ok: raptor-off-by-one
strncat(fullname, firstname, sizeof(fullname) - strlen(fullname) - 1);
}
void bad3(char *string)
{
char filename[BUFSIZE];
// commented-out because of too many false positives: raptor-off-by-one
for (int i = 0; i <= BUFSIZE; i++)
{
char c = getc();
if (c == 'EOF')
{
filename[i] = '\0';
}
filename[i] = getc(stdin);
}
}
void good3(char *string)
{
char filename[BUFSIZE];
// ok: raptor-off-by-one
for (int i = 0; i < BUFSIZE; i++)
{
char c = getc();
if (c == 'EOF')
{
filename[i] = '\0';
}
filename[i] = getc(stdin);
}
}
void test_func()
{
int id_sequence[3];
id_sequence[0] = 123;
id_sequence[1] = 234;
id_sequence[2] = 345;
// ruleid: raptor-off-by-one
id_sequence[3] = 456;
}
void processRawStr(uint8_t *s, size_t sz)
{
uint8_t buf[1024];
memset(buf, 0x0, sizeof(buf));
memcpy(buf, s, sizeof(buf));
// ruleid: raptor-off-by-one
buf[sizeof(buf)] = '\0';
// ...
}
void process_string(char *src)
{
char dest[32];
// commented-out because of too many false positives: raptor-off-by-one
for (i = 0; src[i] && (i <= sizeof(dest)); i++)
dest[i] = src[i];
// ...
return;
}
void get_user(char *user)
{
char buf[1024];
// ruleid: raptor-off-by-one
if (strlen(user) > sizeof(buf))
die("error: user string too long\n");
strcpy(buf, user);
// ...
}
int get_mac(int fd, struct session *session)
{
unsigned int i, n;
n = read_network_integer(fd);
if (n > MAX_MAC)
return 1;
// commented-out because of too many false positives: raptor-off-by-one
for (i = 0; i <= n; i++)
session->mac[i] = read_network_integer(fd);
return 0;
}
int variant1(int argc, char *argv[])
{
char buf[10];
// ruleid: raptor-off-by-one
*(buf + 10) = 'A';
return 0;
}
int variant2(int argc, char *argv[])
{
char bStr[10];
// commented-out because of too many false positives: raptor-off-by-one
for (unsigned i = 1; i <= 10; ++i)
{
bStr[i] = (char)i + 'a';
}
return 0;
}
static LabelText *text_create(char *orig_str, int char_width)
{
int i, j;
char line[256]; /* a line should not exceed this length */
int pos;
int last_space;
int new_line;
LabelText *text = 0;
char *str = 0;
text = calloc(1, sizeof(LabelText));
str = strdup(orig_str);
if (char_width > 0)
{
for (i = 0; i < strlen(str); i++)
if (str[i] == 10)
text->count++;
// ruleid: raptor-off-by-one
if (str[strlen(str) - 1] != 10)
text->count++;
}
return NULL;
}
static LabelText *text_create2(char *orig_str, int char_width)
{
int i, j;
char line[256]; /* a line should not exceed this length */
int pos;
int last_space;
int new_line;
LabelText *text = 0;
char *str = 0;
int length;
text = calloc(1, sizeof(LabelText));
str = strdup(orig_str);
length = strlen(str);
if (char_width > 0)
{
for (i = 0; i < strlen(str); i++)
if (str[i] == 10)
text->count++;
// ruleid: raptor-off-by-one
if (str[strlen(str) - 1] != 10)
text->count++;
}
return NULL;
}
void addLineAfter(struct line *whichLine, char *data)
{
struct line *temp = whichLine->next;
struct line *newLine = (struct line *)malloc(sizeof(struct line));
temp->prev = newLine;
whichLine->next = newLine;
newLine->next = temp;
newLine->prev = whichLine;
// ruleid: raptor-off-by-one
newLine->data = (char *)malloc(strlen(data));
strcpy(newLine->data, data);
newLine->length = strlen(data);
countTabs(newLine);
currentBuffer->numLines++;
}
void addLineAfter_fixed(struct line *whichLine, char *data)
{
struct line *temp = whichLine->next;
struct line *newLine = (struct line *)malloc(sizeof(struct line));
temp->prev = newLine;
whichLine->next = newLine;
newLine->next = temp;
newLine->prev = whichLine;
// ok: raptor-off-by-one
newLine->data = (char *)malloc(strlen(data) + 1);
strcpy(newLine->data, data);
newLine->length = strlen(data);
countTabs(newLine);
currentBuffer->numLines++;
}
void flawed_strdup(const char *input)
{
char *copy;
// ruleid: raptor-off-by-one
copy = (char *)malloc(strlen(input));
strcpy(copy, input);
return copy;
}
void ok_strdup(const char *input)
{
char *copy;
// ok: raptor-off-by-one
copy = (char *)malloc(strlen(input) + 1);
strcpy(copy, input);
return copy;
}
void flawed_strdup2(const char *input)
{
char *copy;
int len = strlen(input);
// ruleid: raptor-off-by-one
copy = (char *)malloc(len);
strcpy(copy, input);
return copy;
}
void ok_strdup2(const char *input)
{
char *copy;
int len = strlen(input);
// ok: raptor-off-by-one
copy = (char *)malloc(len + 1);
strcpy(copy, input);
return copy;
}
int two_dimensions(int argc, char *argv[])
{
char buffer[1][256];
// ruleid: raptor-off-by-one
buffer[0][256] = '!';
// ruleid: raptor-off-by-one
buffer[1][1] = '!';
// ok: raptor-off-by-one
buffer[0][255] = '!';
return 0;
}
void f(const char *str)
{
// ruleid: raptor-off-by-one
char *buffer = malloc(strlen(str));
free(buffer);
}
void f(const char *str)
{
// ok: raptor-off-by-one
char *buffer = malloc(strlen(str) + 1);
free(buffer);
}
void f(const char *str)
{
// ok: raptor-off-by-one
char *buffer = malloc(strlen(str) + 1);
free(buffer);
}
void f(const char *str)
{
size_t len = strlen(str);
// ruleid: raptor-off-by-one
char *buffer = malloc(len);
free(buffer);
}
void f(const char *str)
{
size_t len = strlen(str);
// ok: raptor-off-by-one
char *buffer = malloc(len + 1);
free(buffer);
}
void f(const char *str)
{
size_t len;
len = strlen(str);
// ruleid: raptor-off-by-one
char *buffer = malloc(len);
free(buffer);
}
void f(const char *str)
{
size_t len = strlen(str);
len += 1;
// todook: raptor-off-by-one
char *buffer = malloc(len);
free(buffer);
}
void f(const char *str)
{
size_t len = strlen(str);
if (nondet)
{
len += 1;
}
// ruleid: raptor-off-by-one
char *buffer = malloc(len);
free(buffer);
}
void f(const char *str)
{
size_t len = strlen(str);
if (len)
{
// ruleid: raptor-off-by-one
char *buffer = malloc(len);
free(buffer);
}
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,107 @@
rules:
- id: raptor-off-by-one
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-193: Off-by-one Error"
- "CWE-787: Out-of-bounds Write"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
- https://github.com/struct/mms
message: >-
The software calculates or uses an incorrect maximum or minimum value
that is 1 more, or 1 less, than the correct value.
severity: WARNING
languages:
- c
- cpp
# NOTE: C++ `new` operator and some heap allocation functions are not covered.
# NOTE: some string and memory copy functions are not covered.
# NOTE: `memcpy(dst + 1, p, len)` and similar scenarios are not covered.
# NOTE: pattern `{$len=snprintf(_); malloc($len);}` is not covered.
# NOTE: some other ways to create an array are not covered.
# NOTE: refer also to `metavariable-comparison` to catch larger indexes as in https://github.com/parsiya/semgrep-hotspots/blob/main/cpp/arrays-out-of-bounds-access.yaml
# NOTE: refer also to `cpp.lang.security.strings.alloc-strlen.alloc-strlen` and `cpp.lang.security.strings.missing-nul-cpp-string-memcpy.missing-nul-cpp-string-memcpy`.
pattern-either:
# array access
- pattern: $BUF[sizeof($BUF)] = ...
- patterns:
- pattern: $BUF[$LEN] = ...
- pattern-either:
- pattern-inside: |
$_ $BUF[$LEN];
...
- pattern-inside: |
$_ $BUF[$LEN] = ...;
...
- patterns:
- pattern: |
*($BUF + $LEN) = ...
- pattern-either:
- pattern-inside: |
$_ $BUF[$LEN];
...
- pattern-inside: |
$_ $BUF[$LEN] = ...;
...
# two-dimentional array access
- patterns:
- pattern: $BUF[$X][$Y] = ...
- pattern-either:
- pattern-inside: |
$_ $BUF[$_][$Y];
...
- pattern-inside: |
$_ $BUF[$X][$_];
...
# - pattern: for (<... $I = $NUM ...>; <... $I <= $LEN ...>; <... $I++ ...>) ...
# - pattern: for (<... $I = $NUM ...>; <... $I <= $LEN ...>; <... ++$I ...>) ...
# suspicious loops
# <... $I = 0 ...> is still not supported by Semgrep as of 2025-11-22
# - pattern: for ($_ $I = $NUM; <... $I <= $LEN ...>; <... $I++ ...>) ...
# - pattern: for ($_ $I = $NUM; <... $I <= $LEN ...>; <... ++$I ...>) ...
# - pattern: while (<... $I <= $LEN ...>) ...
# - pattern: do ... while (<... $I <= $LEN ...>);
# strlen vs. sizeof
- pattern: strlen($SRC) > sizeof($DST)
- pattern: strlen($SRC) <= sizeof($DST)
- pattern: sizeof($DST) < strlen($SRC)
- pattern: sizeof($DST) >= strlen($SRC)
# potential strncat misuse
- patterns:
- pattern: strncat($_, $_, $LEN)
- metavariable-pattern:
metavariable: $LEN
patterns:
- pattern-not: $_ - 1
# out-of-bound indexing: strlen($STR) con be 0 leading to a -1 index
- pattern: $STR[strlen($STR) - 1]
- patterns:
- pattern-inside: |
$LEN = strlen($STR) - 1;
...
- pattern: $STR[$LEN]
- patterns:
- pattern-inside: |
$LEN = strlen($STR);
...
- pattern: $STR[$LEN - 1]
# no space allocated for NUL terminator
- pattern: malloc(strlen($STR))
- patterns:
- pattern-inside: |
$LEN = strlen($STR);
...
- pattern: malloc($LEN)
@@ -0,0 +1,74 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#define SIZE 256
int test1()
{
// ...
for (oct_cnt = 1; oct_cnt < 7; oct_cnt++)
{
oct = (u_int8_t)retrieve_rand_int(0xFF);
if (oct_cnt != 1)
// ruleid: raptor-overlapping-source-destination
sprintf(eaddr, "%s:%0x", eaddr, oct);
else
sprintf(eaddr, "%0x", oct);
}
return eaddr;
}
int test2()
{
char buf[SIZE];
// ruleid: raptor-overlapping-source-destination
sprintf(buf, "%s:%s:%s", prepend, buf, append);
// ruleid: raptor-overlapping-source-destination
snprintf(buf, SIZE, "%s:%s", prepend, buf);
// ruleid: raptor-overlapping-source-destination
sprintf(buf, "%s some further text", buf);
return 0;
}
int test2_ok(void)
{
char tmp[SIZE];
// ok: raptor-overlapping-source-destination
snprintf(tmp, SIZE, "%s:%s:%s", prepend, buf, append);
// ok: raptor-overlapping-source-destination
strlcpy(buf, tmp, SIZE);
// ok: raptor-overlapping-source-destination
snprintf(tmp, SIZE, "%s:%s", prepend, buf);
// ok: raptor-overlapping-source-destination
strlcpy(buf, tmp, SIZE);
// ok: raptor-overlapping-source-destination
snprintf(tmp, SIZE, "%s some further text", buf);
// ok: raptor-overlapping-source-destination
strlcpy(buf, tmp, SIZE);
return 0;
}
int test3(char *buf)
{
// ruleid: raptor-overlapping-source-destination
memcpy(buf, buf, 16);
// ruleid: raptor-overlapping-source-destination
strcpy(buf, buf);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,80 @@
rules:
- id: raptor-overlapping-source-destination
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: LOW
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-1260: Improper Handling of Overlap Between Protected Memory Ranges"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://linux.die.net/man/3/sprintf
message: >-
C standards specify that the results are undefined if a call to
copy functions, with the exception of memmove(), would cause copying
to take place between objects that overlap (e.g., if the target
string array and one of the supplied input arguments refer to the
same buffer).
severity: WARNING
languages:
- c
- cpp
# NOTE: `vsprintf`, `vsnprintf`, `swprintf`, and `vswprintf` are not covered.
# NOTE: `strcpy_s`, `strcat_s`, and similar variants are not covered.
pattern-either:
- patterns:
- pattern: $FUN($DST, $DST, ...)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
# strcpy
- pattern: strcpy
- pattern: strncpy
- pattern: stpcpy
- pattern: stpncpy
- pattern: strlcpy
- pattern: strscpy
- pattern: wcscpy
- pattern: wcsncpy
- pattern: wcpcpy
- pattern: wcpncpy
- pattern: wcslcpy
- pattern: _mbscpy
- pattern: _mbsncpy
- pattern: _mbpcpy
- pattern: _mbpncpy
- pattern: _mbslcpy
- pattern: strccpy
- pattern: strcadd
- pattern: streadd
- pattern: strecpy
# strcat
- pattern: strcat
- pattern: strncat
- pattern: strlcat
- pattern: wcscat
- pattern: wcsncat
- pattern: wcslcat
- pattern: _mbscat
- pattern: _mbsncat
- pattern: _mbslcat
# memcpy
- pattern: memcpy
- pattern: memccpy
- pattern: wmemcpy
- pattern: mempcpy
- pattern: wmempcpy
# bcopy
- pattern: bcopy
# sprintf
- pattern: sprintf($DST, ..., $DST, ...)
- pattern: snprintf($DST, $_, ..., $DST, ...)
@@ -0,0 +1,63 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void bad1(char *tmp, char *ptr1, char *ptr2)
{
// ruleid: raptor-pointer-subtraction
memcpy(tmp, ptr1, (ptr2 - ptr1) - 1);
}
int good1(char *tmp, char *ptr1, char *ptr2)
{
if (!tmp || !ptr1 || !ptr2)
return -1;
if (ptr2 <= ptr1)
return -1; // negative or zero-length copy
// the rule should arguably check for this pattern of pointer subtraction with a length check,
// which is a common pattern for safely handling pointer subtraction
// todook: raptor-pointer-subtraction
size_t len = (size_t)(ptr2 - ptr1) - 1;
if (len == 0)
return -1;
memcpy(tmp, ptr1, len);
return 0;
}
void bad2(char *ptr1, char *ptr2)
{
// ruleid: raptor-pointer-subtraction
char *tmp = (char *)malloc(ptr2 - ptr1);
}
struct node
{
int data;
struct node *next;
};
int size(struct node *head)
{
struct node *current = head;
struct node *tail;
while (current != NULL)
{
tail = current;
current = current->next;
}
// ruleid: raptor-pointer-subtraction
return tail - head;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,65 @@
rules:
- id: raptor-pointer-subtraction
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-469: Use of Pointer Subtraction to Determine Size"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://github.com/struct/mms
message: >-
The software subtracts one pointer from another in order to determine
size, but this calculation can be incorrect if the pointers do not
exist in the same memory chunk.
severity: WARNING
languages:
- c
- cpp
# NOTE: some types and combinations are missing; also, function calls are not covered.
pattern-either:
# type-based patterns
- pattern: (char * $_) - (char * $_)
- pattern: (int * $_) - (int * $_)
- pattern: (float * $_) - (float * $_)
- pattern: (double * $_) - (double * $_)
# other patterns
- patterns:
- pattern-either:
- pattern: $PTR1 - $PTR2
- pattern: $PTR2 - $PTR1
- pattern-either:
- pattern-inside: |
$_ * $PTR1;
$_ * $PTR2;
...
- pattern-inside: |
$_ * $PTR1 = ...;
$_ * $PTR2 = ...;
...
- pattern-inside: |
$_ * $PTR1 = ...;
$_ * $PTR2;
...
- pattern-inside: |
$_ * $PTR1;
$_ * $PTR2 = ...;
...
- pattern-inside: |
$_ * $PTR3 = $PTR1;
$_ * $PTR2;
...
- pattern-inside: |
$_ * $PTR2;
$_ * $PTR3 = $PTR1;
...
@@ -0,0 +1,49 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STR_MAX 256
int putName_bad()
{
char name[STR_MAX];
fillInName(name);
// ruleid: raptor-putenv-stack-var
putenv(name);
return 0;
}
int putName_good()
{
char *name = (char *)malloc(STR_MAX);
fillInName(name);
// ok: raptor-putenv-stack-var
putenv(name);
return 0;
}
int putName_good2()
{
static char name[STR_MAX];
fillInName(name);
// ok: raptor-putenv-stack-var
putenv(name);
return 0;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,85 @@
rules:
- id: raptor-putenv-stack-var
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-686: Function Call With Incorrect Argument Type"
- "CWE-562: Return of Stack Variable Address"
owasp:
- A06:2025 - Insecure Design
references:
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
message: >-
The software calls putenv() with a variable that has a short lifetime,
such as a pointer to an automatic variable allocated on the stack. The
correct behavior is to call putenv() with a static/global string.
severity: INFO
languages:
- c
- cpp
# NOTE: global variables declared outside functions and not explicitly tagged as static are not supported.
# NOTE: multi-dimensional arrays and other ways to create an array are not covered.
# NOTE: multiple pointer assignments and other ways to persist after function returns (e.g., output parameter) are not covered.
patterns:
- pattern: putenv($PTR)
- pattern-either:
# array
- patterns:
- pattern-inside: |
$_ $PTR[$_];
...
- pattern-not-inside: |
static $_ $PTR[$_];
...
- patterns:
- pattern-inside: |
$_ $PTR[$_] = ...;
...
- pattern-not-inside: |
static $_ $PTR[$_] = ...;
...
- patterns:
- pattern-inside: |
$_ $PTR[] = ...;
...
- pattern-not-inside: |
static $_ $PTR[] = ...;
...
# pointer to array
- patterns:
- pattern-inside: |
$_ $ARR[$_];
...
$PTR = $ARR;
...
- pattern-not-inside: |
static $_ $ARR[$_];
...
- patterns:
- pattern-inside: |
$_ $ARR[$_] = ...;
...
$PTR = $ARR;
...
- pattern-not-inside: |
static $_ $ARR[$_] = ...;
...
- patterns:
- pattern-inside: |
$_ $ARR[] = ...;
...
$PTR = $ARR;
...
- pattern-not-inside: |
static $_ $ARR[] = ...;
...
@@ -0,0 +1,57 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
// semgrep is currently unable to catch this
// todoruleid: raptor-regex-dos
#define REGEX "^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$"
int regex1()
{
regex_t r1, r2, r3;
int ret;
// ruleid: raptor-regex-dos
char regex[] = "^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$"
ret = regcomp(&r1,
// ruleid: raptor-regex-dos
"^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$",
0);
if (ret)
return 1;
if (ret = regcomp(&r2,
// ruleid: raptor-regex-dos
"^([a-zA-Z0-9])(([\-.]|[_]+)?"
"([a-zA-Z0-9]+))*(@){1}[a-z0-9]+"
"[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$",
0))
return 1;
ret = regcomp(&r3, regex, 0);
if (ret)
return 1;
return 0;
}
int regex2()
{
regex_t r;
int value;
// ok: raptor-regex-dos
value = regcomp(&r, "[:word:]", 0);
if (!value)
{
printf("RegEx compiled successfully.");
return 1;
}
printf("Compilation error.");
return 0;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,55 @@
rules:
- id: raptor-regex-dos
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Denial-of-Service (DoS)
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-1333: Inefficient Regular Expression Complexity"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://semgrep.dev/docs/writing-rules/metavariable-analysis
- https://github.com/semgrep/semgrep/pull/4672
message: >-
The software uses a regular expression with an inefficient, possibly
exponential worst-case computational complexity that consumes excessive
CPU cycles. Poorly constructed regular expressions that exhibit
exponential runtime when fed specifically crafted inputs can cause RegEx
denial of service (ReDoS).
severity: WARNING
languages:
- c
- cpp
# NOTE: the C++ `std::regex` library is not covered.
patterns:
- pattern-either:
- pattern: $FUN($_, $REGEX, $_)
- pattern: |
$STRING = $REGEX;
...
<... $FUN($_, $STRING, $_) ...>;
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: regcomp
- pattern: regncomp
- pattern: regwcomp
- pattern: regwncomp
- pattern: regcomp_l
- pattern: regncomp_l
- pattern: regwcomp_l
- pattern: regwncomp_l
- metavariable-analysis:
analyzer: redos
metavariable: $REGEX
# improve output readability
- focus-metavariable: $REGEX
@@ -0,0 +1,85 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STR_MAX 256
char *getName_bad()
{
char name[STR_MAX];
fillInName(name);
// ruleid: raptor-ret-stack-address
return name;
}
char *getName_good()
{
char *name = (char *)malloc(STR_MAX);
fillInName(name);
// ok: raptor-ret-stack-address
return name;
}
char *getName_good2()
{
static char name[STR_MAX];
fillInName(name);
// ok: raptor-ret-stack-address
return name;
}
char *findF(char *b)
{
char tmpbuf[1024];
char *p = tmpbuf;
memcpy(tmpbuf, b, 1024);
while (*p != '\0')
{
if (*p == 'F')
// ruleid: raptor-ret-stack-address
return p;
p++;
}
return NULL;
}
void fillMem()
{
char a[2048];
memset(a, 'Z', sizeof(a));
}
void recvStr(char *str)
{
char *fPtr = findF(str);
fillMem();
if (fPtr == NULL)
{
printf("No F!");
}
else
{
printf("F = %s", fPtr);
}
}
int *f(void)
{
int local_auto;
// ruleid: raptor-ret-stack-address
return &local_auto;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,141 @@
rules:
- id: raptor-ret-stack-address
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: LOW
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-562: Return of Stack Variable Address"
owasp:
- A06:2025 - Insecure Design
references:
- https://github.com/struct/mms
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
- https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples
- https://rules.sonarsource.com/c/type/Bug/RSPEC-946
message: >-
A function returns the address of a stack variable, which will cause
unintended program behavior, typically in the form of a crash.
severity: INFO
languages:
- c
- cpp
# NOTE: global variables declared outside functions and not explicitly tagged as static are not supported.
# NOTE: multi-dimensional arrays and other ways to create an array are not covered.
# NOTE: multiple pointer assignments and other ways to persist after function returns (e.g., output parameter) are not covered.
# NOTE: a dedicated rule for C++ types/constructs should be implemented (see `cpp.lang.security.strings.return-c-str.return-c-str` and `cpp.lang.security.containers.std-return-data.std-return-data`).
pattern-either:
- patterns:
- pattern: return $PTR;
- pattern-either:
# array
- patterns:
- pattern-inside: |
$_ $PTR[$_];
...
- pattern-not-inside: |
static $_ $PTR[$_];
...
- patterns:
- pattern-inside: |
$_ $PTR[$_] = ...;
...
- pattern-not-inside: |
static $_ $PTR[$_] = ...;
...
- patterns:
- pattern-inside: |
$_ $PTR[] = ...;
...
- pattern-not-inside: |
static $_ $PTR[] = ...;
...
# pointer to array
- patterns:
- pattern-inside: |
$_ $ARR[$_];
...
$PTR = $ARR;
...
- pattern-not-inside: |
static $_ $ARR[$_];
...
- patterns:
- pattern-inside: |
$_ $ARR[$_] = ...;
...
$PTR = $ARR;
...
- pattern-not-inside: |
static $_ $ARR[$_] = ...;
...
- patterns:
- pattern-inside: |
$_ $ARR[] = ...;
...
$PTR = $ARR;
...
- pattern-not-inside: |
static $_ $ARR[] = ...;
...
- patterns:
# address of local variable
- pattern: return &$VAR;
- pattern-either:
- patterns:
- pattern-inside: |
$_ $VAR;
...
- pattern-not-inside: |
static $_ $VAR;
...
- patterns:
- pattern-inside: |
$_ $VAR = ...;
...
- pattern-not-inside: |
static $_ $VAR = ...;
...
- patterns:
- pattern-inside: |
$_ $VAR[$_];
...
- pattern-not-inside: |
static $_ $VAR[$_];
...
- patterns:
- pattern-inside: |
$_ $VAR[$_] = ...;
...
- pattern-not-inside: |
static $_ $VAR[$_] = ...;
...
- patterns:
- pattern-inside: |
$_ $VAR[] = ...;
...
- pattern-not-inside: |
static $_ $VAR[] = ...;
...
- patterns:
- pattern-inside: |
$_ * $VAR;
...
- pattern-not-inside: |
static $_ * $VAR;
...
- patterns:
- pattern-inside: |
$_ * $VAR = ...;
...
- pattern-not-inside: |
static $_ * $VAR = ...;
...
@@ -0,0 +1,239 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
// https://pwning.systems/posts/php_filter_var_shenanigans/
static int _php_filter_validate_domain(char *domain, int len, zend_long flags)
{
char *e, *s, *t;
size_t l;
int hostname = flags & FILTER_FLAG_HOSTNAME;
unsigned char i = 1;
s = domain;
// ruleid: raptor-signed-unsigned-conversion
l = len;
e = domain + l;
t = e - 1;
// ...
return 0;
}
// https://blog.quarkslab.com/heap-overflow-in-openbsds-slaacd-via-router-advertisement.html
char *
parse_dnssl(char *data, int datalen)
{
int len, pos;
char *nssl, *nsslp;
// ruleid: raptor-signed-unsigned-conversion
if ((nssl = calloc(1, datalen + 1)) == NULL)
{ // false positive
log_warn("malloc");
return NULL;
}
nsslp = nssl;
pos = 0;
do
{
len = data[pos];
if (len > 63 || len + pos + 1 > datalen)
{
free(nssl);
log_warnx("invalid label in DNSSL");
return NULL;
}
if (len == 0)
{
if (pos < datalen && data[pos + 1] != 0)
*nsslp++ = ' ';
else
break;
}
else
{
if (pos != 0 && data[pos - 1] != 0)
*nsslp++ = '.';
// ruleid: raptor-signed-unsigned-conversion
memcpy(nsslp, data + pos + 1, len);
nsslp += len;
}
pos += len + 1;
} while (pos < datalen);
if (len != 0)
{
free(nssl);
log_warnx("invalid label in DNSSL");
return NULL;
}
return nssl;
}
// http://www.phrack.org/issues/60/10.html#article
int copy_something1(char *buf, int len)
{
char kbuf[800];
if (len > sizeof(kbuf))
{
return -1;
}
// ruleid: raptor-signed-unsigned-conversion
return memcpy(kbuf, buf, len);
}
int copy_something2(char *buf, size_t len)
{
char kbuf[800];
if (!buf || len == 0 || len > sizeof(kbuf))
return -1;
// ok: raptor-signed-unsigned-conversion
memcpy(kbuf, buf, len);
return 0;
}
// ruleid: raptor-signed-unsigned-conversion
unsigned int readdata()
{
int amount = 0;
if (result == ERROR)
amount = -1;
return amount;
}
// ruleid: raptor-signed-unsigned-conversion
unsigned int readdata2()
{
int amount = 0;
amount = accessmainframe();
return amount;
}
void copy_memory()
{
int size = 256;
// ruleid: raptor-signed-unsigned-conversion
memcpy(destBuf, srcBuf, size);
}
void test_func(int argc, char **argv)
{
char path[256];
char *input;
int i;
unsigned int sz;
i = GetUntrustedInt();
if (i > 256)
{
DiePainfully("go away!\n");
}
// ruleid: raptor-signed-unsigned-conversion
sz = i;
// ruleid: raptor-signed-unsigned-conversion
strncpy(path, input, i);
path[255] = '\0';
printf("Path is: %s\n", path);
}
void blowup_stack()
{
int a = 5, b = 6;
// ruleid: raptor-signed-unsigned-conversion
size_t len = a - b;
char buf[len];
}
void disaster()
{
int len;
len = get_len_field();
// ruleid: raptor-signed-unsigned-conversion
snprintf(dst, len, "%s", src);
}
int watch_dns_ptr()
{
char *indx;
int count;
char nameStr[256];
// ...
memset(nameStr, '\0', sizeof(nameStr));
// ...
indx = (char *)(pkt + rr_offset);
count = (char)*indx;
while (count)
{
(char *)indx++;
// ruleid: raptor-signed-unsigned-conversion
strncat(nameStr, (char *)indx, count);
indx += count;
count = (char)*indx;
// there's also a strncat() misuse here
strncat(nameStr, ".", sizeof(nameStr) - strlen(nameStr));
}
nameStr[strlen(nameStr) - 1] = '\0';
return 0;
}
// https://vulncat.fortify.com/
void TypeConvert()
{
char input[MAX];
char output[MAX];
fillBuffer(input);
int len = getInputLength();
if (len <= MAX)
{
// ruleid: raptor-signed-unsigned-conversion
memcpy(output, input, len);
}
// ...
}
// https://vulncat.fortify.com/
char *processNext(char *strm)
{
char buf[512];
int len = *(int *)strm;
strm += sizeof(len);
if (len <= 512)
{
// ruleid: raptor-signed-unsigned-conversion
memcpy(buf, strm, len);
process(buf);
return strm + len;
}
else
{
return -1;
}
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,22 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <sys/types.h>
SharedMemory *SharedMemory::New(Plugin *plugin, off_t length)
{
void *map_addr = NULL;
// ruleid: raptor-signed-unsigned-conversion
size_t size = static_cast<size_t>(length);
NaClHandle handle = nacl::CreateMemoryObject(size);
struct NaClDescImcShm *imc_desc = reinterpret_cast<struct NaClDescImcShm *>(malloc(sizeof(*imc_desc)));
struct NaClDesc *desc = reinterpret_cast<struct NaClDesc *>(imc_desc);
dprintf(("SharedMemory::New(%p, 0x%08x)\n ", plugin, (unsigned)length));
NaClDescImcShmCtor(imc_desc, handle, length);
return New(plugin, desc);
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,145 @@
rules:
- id: raptor-signed-unsigned-conversion
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Other Security
likelihood: MEDIUM
impact: MEDIUM
confidence: LOW
technology:
- c
- cpp
cwe:
- "CWE-195: Signed to Unsigned Conversion Error"
- "CWE-196: Unsigned to Signed Conversion Error"
- "CWE-194: Unexpected Sign Extension"
- "CWE-191: Integer Underflow (Wrap or Wraparound)"
- "CWE-681: Incorrect Conversion between Numeric Types"
- "CWE-789: Memory Allocation with Excessive Size Value"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
- https://github.com/struct/mms
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
- http://www.phrack.org/issues/60/10.html#article
- https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples
message: >-
The software uses a signed primitive and performs a cast to an
unsigned primitive, or uses an unsigned primitive and performs a cast
to a signed primitive, which can produce an unexpected value.
When the result of a function is to be used as a size parameter,
using negative return values can have unexpected results.
Although less frequent an issue, unsigned-to-signed conversion can be
the precursor to buffer underwrite conditions. Buffer underwrites
occur frequently when large unsigned values are cast to signed values,
and then used as indexes into a buffer or for pointer arithmetic.
severity: WARNING
languages:
- c
- cpp
# NOTE: the deep expression operator is necessary to catch some matches because C/C++ integer promotions do not seem entirely supported by Semgrep; this may generate lots of false positives.
# NOTE: some types (e.g. `char`, `short`, `long`), functions (e.g., widechar and some alloc functions, custom wrappers), and use cases (e.g., comparisons) are not covered.
# NOTE: `wmemcpy`, `wmemmove`, and `wmemset` are not covered.
# NOTE: `memcpy_s`, `memmove_s`, `memset_explicit`, and similar variants are not covered.
# NOTE: `strcpy_s`, `strcat_s`, and similar variants are not covered.
# NOTE: try to avoid false positives where possible.
pattern-either:
# signed to unsigned
- patterns:
- pattern-either:
- pattern: (unsigned int $_) = <... (int $_) ...>
- pattern: (unsigned $_) = <... (int $_) ...>
- pattern: (size_t $_) = <... (int $_) ...>
- pattern: (size_t $_) = <... (off_t $_) ...>
- pattern-not: $_ = 0
- patterns:
- pattern-either:
- pattern: |
unsigned int $FUN(...)
{
...
return (int $_);
}
- pattern: |
unsigned $FUN(...)
{
...
return (int $_);
}
- pattern: |
size_t $FUN(...)
{
...
return (int $_);
}
- pattern: |
size_t $FUN(...)
{
...
return (off_t $_);
}
# improve output readability
- focus-metavariable: $FUN
- pattern: strncpy($_, $_, (int $_))
- pattern: stpncpy($_, $_, (int $_))
- pattern: strncat($_, $_, (int $_))
- pattern: strlcpy($_, $_, (int $_))
- pattern: strscpy($_, $_, (int $_))
- pattern: strlcat($_, $_, (int $_))
- pattern: snprintf($_, (int $_), ...)
- pattern: vsnprintf($_, (int $_), ...)
- pattern: swprintf($_, (int $_), ...)
- pattern: vswprintf($_, (int $_), ...)
- pattern: getcwd($_, (int $_))
- pattern: memcpy($_, $_, (int $_))
- pattern: mempcpy($_, $_, (int $_))
- pattern: memccpy($_, $_, $_, (int $_))
- pattern: memmove($_, $_, (int $_))
- pattern: memset($_, $_, (int $_))
- pattern: bcopy($_, $_, (int $_))
- pattern: alloca((int $_))
- pattern: malloc((int $_))
- pattern: calloc($_, (int $_))
- pattern: calloc((int $_), $_)
- pattern: realloc($_, (int $_))
- pattern: read($_, $_, (int $_))
- pattern: recv($_, $_, (int $_), $_)
- pattern: recvfrom($_, $_, (int $_), $_, ...)
- pattern: fread($_, (int $_), $_, $_)
# unsigned to signed
- pattern: (int $_) = <... (unsigned int $_) ...>
- pattern: (int $_) = <... (unsigned $_) ...>
- pattern: (int $_) = <... (size_t $_) ...>
- pattern: (off_t $_) = <... (size_t $_) ...>
- patterns:
- pattern-either:
- pattern: |
int $FUN(...)
{
...
return (unsigned int $_);
}
- pattern: |
int $FUN(...)
{
...
return (unsigned $_);
}
- pattern: |
int $FUN(...)
{
...
return (size_t $_);
}
- pattern: |
off_t $FUN(...)
{
...
return (size_t $_);
}
# improve output readability
- focus-metavariable: $FUN
@@ -0,0 +1,107 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
void bt_mesh_beacon_priv_random_get(uint8_t *random, size_t size)
{
// ruleid: raptor-suspicious-assert
__ASSERT(size <= sizeof(priv_random.val), "Invalid random value size %u", size);
memcpy(random, priv_random.val, size);
}
static inline int send_sf(struct isotp_send_ctx *ctx)
{
/* ... */
if (ctx->tx_addr.use_ext_addr)
{
frame.data[index++] = ctx->tx_addr.ext_addr;
}
frame.data[index++] = ISOTP_PCI_TYPE_SF | len;
// ruleid: raptor-suspicious-assert
__ASSERT_NO_MSG(len <= ISOTP_CAN_DL - index);
memcpy(&frame.data[index], data, len);
/* ... */
return 0;
}
static inline void assert_buf_len(int need, int have)
{
// ruleid: raptor-suspicious-assert
__ASSERT(need < have, "OOM at build command: need:%d have:%d",
need, have);
}
static int line_out_drop_mode(void)
{
/* line cannot be empty */
// ruleid: raptor-suspicious-assert
__ASSERT_NO_MSG(line_pos > line_buf);
/* Handle the case if line contains only '\n' */
if (line_pos - line_buf == 1)
{
line_pos++;
}
*(line_pos - 1) = '\r';
*line_pos++ = '\n';
if (drop_cnt > 0 && !drop_warn)
{
int cnt = MIN(drop_cnt, DROP_MAX);
// ruleid: raptor-suspicious-assert
__ASSERT_NO_MSG(line_pos - line_buf <= MESSAGE_SIZE);
memmove(line_buf + DROP_MSG_LEN, line_buf, line_pos - line_buf);
(void)memcpy(line_buf, drop_msg, DROP_MSG_LEN);
line_pos += DROP_MSG_LEN;
drop_warn = 1;
/* ... */
}
return 0;
}
void arch_irq_offload(irq_offload_routine_t routine, const void *parameter)
{
offload_params[CURR_CPU].fn = routine;
offload_params[CURR_CPU].arg = parameter;
compiler_barrier();
z_arc_v2_aux_reg_write(_ARC_V2_AUX_IRQ_HINT, IRQ_OFFLOAD_LINE);
/* ... */
/* If _current was aborted in the offload routine, we shouldn't be here */
// ok: raptor-suspicious-assert
__ASSERT_NO_MSG((_current->base.thread_state & _THREAD_DEAD) == 0);
}
int process_sub(FILE *data_file, FILE *struct_file)
{
FIND_T fInfo;
FIND_RET_T fret;
int filesProcessed = 0;
if (processSubs)
{
/* process subs recursively */
size_t sublen = strlen(curSubdir);
size_t freelen = sizeof(curSubdir) - sublen - 1;
// ruleid: raptor-suspicious-assert
LWIP_ASSERT("sublen < sizeof(curSubdir)", sublen < sizeof(curSubdir));
fret = FINDFIRST_DIR("*", &fInfo);
/* ... */
}
return 0;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,41 @@
rules:
- id: raptor-suspicious-assert
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Other Security
likelihood: MEDIUM
impact: HIGH
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-754: Improper Check for Unusual or Exceptional Conditions"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://legends2k.github.io/note/assert_vs_if/
- https://github.com/struct/mms
message: >-
Most codebases define assertion macros which compile to a no-op on
non-debug builds. If assertions are the only line of defense against
untrusted input, the software may be exposed to attacks that leverage
the lack of proper input checks.
severity: WARNING
languages:
- c
- cpp
# NOTE: other conditions (i.e., equality and inequality) might be security-relevant as well.
# NOTE: other kinds of assertion macros (e.g., `REQUIRE`, `DCHECK`, `ENSURE`, etc.) and custom wrappers are not covered.
patterns:
- pattern-either:
- pattern: $ASSERT(..., <... $_ < $_ ...>, ...)
- pattern: $ASSERT(..., <... $_ <= $_ ...>, ...)
- pattern: $ASSERT(..., <... $_ > $_ ...>, ...)
- pattern: $ASSERT(..., <... $_ >= $_ ...>, ...)
- metavariable-regex:
metavariable: $ASSERT
regex: '(?i)^\w*assert\w*\s*$'
@@ -0,0 +1,283 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void bad1()
{
char *src, *dst;
int left;
while (*src && left)
{
*dst++ = *src++;
// ruleid: raptor-typos
if (left = 0)
{
die("badlen");
}
left--;
}
}
void good1(char *path, char *dir, char *obj)
{
char *last;
// ok: raptor-typos
if ((last = strrchr(path, '/')) != NULL)
{
strcpy(obj, last + 1);
if (last == path)
{
strcpy(dir, "/");
}
else
{
*last = '\0';
strcpy(dir, path);
*last = '/';
}
}
else
{
dir[0] = dir[0] = '\0';
}
}
int bad2(char *username)
{
int f;
f = get_security_flags(username);
// ruleid: raptor-typos
if (f = FLAG_AUTHENTICATED)
{
return LOGIN_OK;
}
return LOGIN_FAILED;
}
void bad3(char *src, char *dst)
{
// ruleid: raptor-typos
if (get_string(src) &&
check_for_overflow(src) & copy_string(dst, src))
{
printf("string safely copied\n");
}
}
void bad4(char *src, int len)
{
char dst[256];
// ruleid: raptor-typos
if (len > 0 && len <= sizeof(dst))
;
memcpy(dst, src, len);
}
void bad5(char *src, char *dst)
{
int i;
// ruleid: raptor-typos
for (i == 5; src[i] && i < 10; i++)
{
dst[i - 5] = src[i];
}
}
void bad6(char *userinput)
{
// ruleid: raptor-typos
char buf[040];
// ok: raptor-typos
char buf[0x40];
snprintf(buf, 40, "%s", userinput);
}
void bad7()
{
// ruleid: raptor-typos
if (frag_len &
!BUF_MEM_grow_clean(s->init_buf, (int)frag_len +
DTLS1_HM_HEADER_LENGTH + s->init_num))
{
SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, ERR_R_BUF_LIB);
goto err;
}
}
void bad8(int j)
{
int i = 10;
// ruleid: raptor-typos
i = +j;
}
int isValid(int value)
{
// ruleid: raptor-typos
if (value = 100)
{
printf("Value is valid\n");
return (1);
}
printf("Value is not valid\n");
return (0);
}
void processString(char *str)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if (isalnum(str[i]))
{
processChar(str[i]);
}
// ruleid: raptor-typos
else if (str[i] = ':')
{
movingToNewInput();
}
}
}
#define SIZE 50
int *tos, *p1, stack[SIZE];
void push(int i)
{
p1++;
if (p1 == (tos + SIZE))
{
printf("Print stack overflow error message and exit\n");
}
// ruleid: raptor-typos
*p1 == i;
}
int pop(void)
{
if (p1 == tos)
{
printf("Print stack underflow error message and exit\n");
}
p1--;
return *(p1 + 1);
}
void test1()
{
// ruleid: raptor-typos
if ((nowtok == tok_mb_cur_max && result->mb_cur_max != 0) || (nowtok == tok_mb_cur_max && result->mb_cur_max != 0))
lr_error(cmfile, _("duplicate definition of <%s>"), nowtok == tok_mb_cur_min ? "mb_cur_min" : "mb_cur_max");
}
int test2()
{
e = borg_extract_dir(y1, x1, y2, x2);
// ruleid: raptor-typos
if ((ay <= 1) && (ay <= 1))
return (e);
if (ay > ax)
{
d = (y1 < y2) ? 2 : 8;
if (borg_cave_floor_bold(y1 + ddy[d], x1 + ddx[d]))
return (d);
}
}
void test3()
{
char *at;
char mntfrombuf[MNAMELEN];
char *mntfromptr;
mntfromptr = mp->f_mntfromname;
switch (mp->f_type)
{
case MOUNT_TYPE_NFS:
case MOUNT_TYPE_NFS3:
at = strchr(mp->f_mntfromname, '@');
// ruleid: raptor-typos
if (at != '\0')
{
xstrlcpy(mntfrombuf, (at + 1), sizeof(mntfrombuf));
}
}
}
int test4()
{
fsa_node_addr *prev_node = NULL;
char *cur = nodes_arg; /* point to start of string */
for (int i = 0; i < strlen(nodes_arg); i++)
{
if (nodes_arg[i] != ',' && (nodes_arg[i] < '0' || nodes_arg[i] > '9'))
{
fsa_error(LOG_ERR, "Invalid nodes argument: %s\n", nodes_arg);
return 1;
}
}
// ruleid: raptor-typos
while (cur != NULL && cur != '\0')
{
int node_num = (int)strtol(cur, (char **)NULL, 10);
if (node_num == 0 && errno != 0)
{
do_someting();
}
}
}
void test5()
{
// ruleid: raptor-typos
if (strcpy(szbuf1, "Manager") == 0)
{
do_something();
}
}
void test6()
{
// ...
// ok: raptor-typos
assert("in this state, the rx chain should be empty", state->rx == NULL);
}
int wgetnstr(WINDOW *win, char *str, int n)
{
char *_str;
int c;
if (n == 0)
{
// ruleid: raptor-typos
str = '\0';
return OK;
}
_str = str;
}
int main(int argc, char *argv[])
{
tos = stack;
p1 = stack;
// ...
return 0;
}
@@ -0,0 +1,105 @@
rules:
- id: raptor-typos
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Other Security
likelihood: LOW
impact: LOW
confidence: LOW
technology:
- c
- cpp
cwe:
- "CWE-480: Use of Incorrect Operator"
- "CWE-481: Assigning instead of Comparing"
- "CWE-482: Comparing instead of Assigning"
- "CWE-483: Incorrect Block Delimitation"
- "CWE-705: Incorrect Control Flow Scoping"
- "CWE-561: Dead Code"
- "CWE-1164: Irrelevant Code"
owasp:
- A08:2025 - Software or Data Integrity Failures
references:
- https://g.co/kgs/PCHQjJ
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
message: >-
The programmer accidentally uses the wrong operator, which changes
the application logic in security-relevant ways. This rule also covers
some other common typo patterns.
severity: INFO
languages:
- c
- cpp
# NOTE: common issues with comments are not covered.
# NOTE: consider adding a `focus-metavariable` where applicable to improve output readability.
# NOTE: custom wrappers to assertion macros are not covered.
pattern-either:
# == instead of = in assignment (the ternary operator is not supported by Semgrep)
# NOTE: the semicolon at the end of the pattern should be removed, but this would generate many false positives on top of those already generated by the current pattern, so we keep it for now.
- pattern: for ($_ == $_; $_; $_) ...
- patterns:
- pattern: $_ == $_;
- pattern-not-inside: return $_;
- pattern-not-inside: assert(...);
# = instead of == in comparison
- patterns:
- pattern: if (<... $EXPR1 = $EXPR2 ...>) ...
- pattern-not-inside: if (<... ($EXPR1 = $EXPR2) == $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 = $EXPR2) != $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 = $EXPR2) < $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 = $EXPR2) <= $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 = $EXPR2) > $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 = $EXPR2) >= $_ ...>) ...
# & instead of && in comparison
- patterns:
- pattern: if (<... $EXPR1 & $EXPR2 ...>) ...
- pattern-not-inside: if (<... ($EXPR1 & $EXPR2) == $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 & $EXPR2) != $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 & $EXPR2) < $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 & $EXPR2) <= $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 & $EXPR2) > $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 & $EXPR2) >= $_ ...>) ...
# | instead of || in comparison
- patterns:
- pattern: if (<... $EXPR1 | $EXPR2 ...>) ...
- pattern-not-inside: if (<... ($EXPR1 | $EXPR2) == $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 | $EXPR2) != $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 | $EXPR2) < $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 | $EXPR2) <= $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 | $EXPR2) > $_ ...>) ...
- pattern-not-inside: if (<... ($EXPR1 | $EXPR2) >= $_ ...>) ...
# =+ instead of += (and =- instead of -=)
- pattern: $_ =+ $_
# - pattern: $EXPR1 =- $EXPR2
# duplicate expressions
- pattern: ($EXPR && $EXPR)
- pattern: ($EXPR || $EXPR)
- pattern: ($EXPR == $EXPR)
- pattern: ($EXPR != $EXPR)
- pattern: ($EXPR < $EXPR)
- pattern: ($EXPR <= $EXPR)
- pattern: ($EXPR > $EXPR)
- pattern: ($EXPR >= $EXPR)
# assigning or comparing a char literal to a pointer (some types and literals are missing)
- pattern: (char * $_) = '\0'
- pattern: (char * $_) == '\0'
- pattern: (char * $_) != '\0'
# use of a string copy function instead of a string compare function in a condition
- pattern: if (<... strcpy(...) ...>) ...
- pattern: if (<... strncpy(...) ...>) ...
# ; at the end of if or for statement (empty else block not covered)
- pattern: if ($_);
- pattern: for ($_; $_; $_);
# accidental octal conversion
- patterns:
- pattern-either:
- pattern: $_ $_[$LEN];
- pattern: $_ $_[$LEN] = ...;
- metavariable-regex:
metavariable: $LEN
regex: "^0[^xX].*"
# missing {} in if statement (too many false positives)
# - pattern: if ($COND) $BODY;
@@ -0,0 +1,99 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
#define MEMSIZE 256
void alloc_memory()
{
// ruleid: raptor-unchecked-ret-malloc
char *ptr = (char *)malloc(MEMSIZE);
}
int alloc_memory_and_check1()
{
// ok: raptor-unchecked-ret-malloc
char *ptr = (char *)malloc(MEMSIZE);
if (ptr == NULL)
return -1;
// ...
return 0;
}
int alloc_memory_and_check2()
{
char *ptr;
// ok: raptor-unchecked-ret-malloc
if ((ptr = (char *)malloc(MEMSIZE)) != NULL)
{
// ...
return 0;
}
return -1;
}
int alloc_memory_and_check3()
{
// ok: raptor-unchecked-ret-malloc
char *ptr = (char *)malloc(MEMSIZE);
if (!ptr)
return -1;
// ...
return 0;
}
int alloc_memory_and_check4()
{
char *ptr;
// ok: raptor-unchecked-ret-malloc
if (!(ptr = (char *)malloc(MEMSIZE)))
return -1;
// ...
return 0;
}
void test_func()
{
// ruleid: raptor-unchecked-ret-malloc
buf = (char *)malloc(req_size);
strncpy(buf, xfer, req_size);
}
void test_func2()
{
// ruleid: raptor-unchecked-ret-malloc
AStruct *s = (AStruct *)malloc(user_len);
s[user_offset] = 0xff;
}
int append_data(struct databuf *buf, char *src, size_t len)
{
size_t new_size = buf->used + len + EXTRA;
if (new_size < len)
return -1;
if (new_size > buf->allocated_length)
{
// ruleid: raptor-unchecked-ret-malloc
buf->data = (char *)realloc(buf->data, new_size);
buf->allocated_length = new_size;
}
memcpy(buf->data + buf->used, src, len);
buf->used += len;
return 0;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,77 @@
rules:
- id: raptor-unchecked-ret-malloc
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-252: Unchecked Return Value"
- "CWE-690: Unchecked Return Value to NULL Pointer Dereference"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
- https://github.com/struct/mms
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
message: >-
The software does not check the return value from a method or
function, which can prevent it from detecting unexpected states and
conditions.
severity: WARNING
languages:
- c
- cpp
# NOTE: custom wrappers are not covered.
# NOTE: for another approach to NULL pointer dereferencing detection, refer to `cpp.lang.security.memory.null-deref.null-library-function.null-library-function`.
patterns:
- pattern-either:
- pattern: $RET = $FUN(...)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: malloc
- pattern: calloc
- pattern: realloc
- pattern: reallocf
- pattern: valloc
- pattern: aligned_alloc
- pattern: strdup
- pattern: strndup
- pattern-not-inside: |
$FUN(...);
...
if (<... $RET ...>) ...
# no need to explicitly check the following patterns, as the deep expression operator above will already match them
# - pattern-not-inside: |
# $FUN(...);
# ...
# if (<... $RET == NULL ...>) ...
# - pattern-not-inside: |
# $FUN(...);
# ...
# if (<... NULL == $RET ...>) ...
# - pattern-not-inside: |
# $FUN(...);
# ...
# if (<... $RET != NULL ...>) ...
# - pattern-not-inside: |
# $FUN(...);
# ...
# if (<... NULL != $RET ...>) ...
# - pattern-not-inside: |
# $FUN(...);
# ...
# if (<... !$RET ...>) ...
- pattern-not-inside: <... $_ == NULL ...>
- pattern-not-inside: <... NULL == $_ ...>
- pattern-not-inside: <... $_ != NULL ...>
- pattern-not-inside: <... NULL != $_ ...>
- pattern-not-inside: <... !$_ ...>
@@ -0,0 +1,68 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <pwd.h>
#include <uuid/uuid.h>
static int
parseuid_bad(const char *s, uid_t *uid)
{
struct passwd *pw;
const char *errstr;
if ((pw = getpwnam(s)) != NULL)
{
*uid = pw->pw_uid;
return 0;
}
#if !defined(__linux__) && !defined(__NetBSD__)
*uid = strtonum(s, 0, UID_MAX, &errstr);
#else
// ruleid: raptor-unchecked-ret-scanf
sscanf(s, "%d", uid);
#endif
if (errstr)
return -1;
return 0;
}
static int
parseuid_good(const char *s, uid_t *uid)
{
struct passwd *pw;
#if !defined(__linux__) && !defined(__NetBSD__)
const char *errstr = NULL;
#else
int status;
#endif
if ((pw = getpwnam(s)) != NULL)
{
*uid = pw->pw_uid;
return 0;
}
#if !defined(__linux__) && !defined(__NetBSD__)
*uid = strtonum(s, 0, UID_MAX, &errstr);
if (errstr)
return -1;
#else
// ok: raptor-unchecked-ret-scanf
status = sscanf(s, "%d", uid);
if (status != 1)
return -1;
#endif
return 0;
}
int main(int argc, char *argv[])
{
int i = 0, j = 0;
printf("Enter two numbers:\n");
// ruleid: raptor-unchecked-ret-scanf
scanf("%d %d", &i, &j);
printf("Result = %d\n", i / j);
return 0;
}
@@ -0,0 +1,65 @@
rules:
- id: raptor-unchecked-ret-scanf
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Other Security
likelihood: MEDIUM
impact: LOW
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-252: Unchecked Return Value"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://codeql.github.com/codeql-query-help/cpp/cpp-missing-check-scanf/
message: >-
The software does not check the return value from a method or
function, which can prevent it from detecting unexpected states and
conditions.
severity: WARNING
languages:
- c
- cpp
patterns:
- pattern: $FUN(...)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: scanf
- pattern: __isoc99_scanf
- pattern: vscanf
- pattern: __isoc99_vscanf
- pattern: fscanf
- pattern: __isoc99_fscanf
- pattern: vfscanf
- pattern: __isoc99_vfscanf
- pattern: sscanf
- pattern: __isoc99_sscanf
- pattern: vsscanf
- pattern: __isoc99_vsscanf
- pattern: wscanf
- pattern: vwscanf
- pattern: fwscanf
- pattern: vfwscanf
- pattern: swscanf
- pattern: vswscanf
- pattern-not-inside: $_ = $FUN(...)
- pattern-not-inside: <... $FUN(...) == $_ ...>
- pattern-not-inside: <... $_ == $FUN(...) ...>
- pattern-not-inside: <... $FUN(...) != $_ ...>
- pattern-not-inside: <... $_ != $FUN(...) ...>
- pattern-not-inside: <... $FUN(...) < $_ ...>
- pattern-not-inside: <... $_ > $FUN(...) ...>
- pattern-not-inside: <... $FUN(...) <= $_ ...>
- pattern-not-inside: <... $_ >= $FUN(...) ...>
- pattern-not-inside: <... $FUN(...) > $_ ...>
- pattern-not-inside: <... $_ < $FUN(...) ...>
- pattern-not-inside: <... $FUN(...) >= $_ ...>
- pattern-not-inside: <... $_ <= $FUN(...) ...>
- pattern-not-inside: return $FUN(...);
@@ -0,0 +1,42 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <unistd.h>
void drop_priv_perm()
{
// ruleid: raptor-unchecked-ret-setuid-seteuid
setuid(getuid());
}
int drop_priv_perm2()
{
// ok: raptor-unchecked-ret-setuid-seteuid
if (!setuid(getuid()))
{
// ...
return 0;
}
return -1;
}
void drop_priv_temp()
{
// ruleid: raptor-unchecked-ret-setuid-seteuid
seteuid(getuid());
}
int drop_priv_temp2()
{
// ok: raptor-unchecked-ret-setuid-seteuid
if (seteuid(getuid()) < 0)
return -1;
// ...
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,49 @@
rules:
- id: raptor-unchecked-ret-setuid-seteuid
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Improper Authorization
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-252: Unchecked Return Value"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://lwn.net/Articles/451985/
- https://www.usenix.org/legacy/events/sec02/full_papers/chen/chen.pdf
- https://www.openwall.com/lists/oss-security/2023/12/30/4
message: >-
The software does not check the return value from a method or
function, which can prevent it from detecting unexpected states and
conditions. If the program calls a function to drop privileges but
does not check the return code to ensure that privileges were
successfully dropped, then the program will continue to operate with
the higher privileges.
severity: WARNING
languages:
- c
- cpp
patterns:
- pattern: $FUN(...)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: setuid
- pattern: seteuid
- pattern-not-inside: $_ = $FUN(...)
- pattern-not-inside: <... $FUN(...) == $_ ...>
- pattern-not-inside: <... $_ == $FUN(...) ...>
- pattern-not-inside: <... $FUN(...) != $_ ...>
- pattern-not-inside: <... $_ != $FUN(...) ...>
- pattern-not-inside: <... $FUN(...) < $_ ...>
- pattern-not-inside: <... $_ > $FUN(...) ...>
- pattern-not-inside: <... !$FUN(...) ...>
- pattern-not-inside: return $FUN(...);
@@ -0,0 +1,297 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#define BUFSIZE 256
#define SIZE(x, y) (sizeof(x)((y)(x)))
void copy_string(char *string)
{
char buf[BUFSIZE];
size_t length;
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
length = snprintf(buf, BUFSIZE, "%s", string);
// use length to access buf
}
void bad()
{
char buf[1024], *ptr;
ptr = buf;
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
ptr += snprintf(ptr, SIZE(buf, ptr), "user: %s\n", username);
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
ptr += snprintf(ptr, SIZE(buf, ptr), "pass: %s\n", password);
}
#define PRIx64 "llx"
void bad2()
{
// ...
// excluded due to the format string regex used to reduce false positives
// todoruled: raptor-unsafe-ret-snprintf-vsnprintf
len = snprintf(buf, sizeof(buf) - 1,
"Fluent Bit has been running: "
" %i day%s, %i hour%s, %i minute%s and %i second%s",
days, (days > 1) ? "s" : "", hours,
(hours > 1) ? "s" : "", minutes,
(minutes > 1) ? "s" : "", seconds,
(seconds > 1) ? "s" : "");
// ...
}
int log(int fd, char *fmt, ...)
{
char buffer[BUFSIZE];
int n;
va_list ap;
va_start(ap, fmt);
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
n = vsnprintf(buffer, sizeof(buffer), fmt, ap);
if (n >= BUFSIZE - 2)
buffer[sizeof(buffer) - 2] = '\0';
strcat(buffer, "\n");
va_end(ap);
write_log(fd, buffer, strlen(buffer));
return 0;
}
#include <iostream>
int test()
{
char myname[5];
// there is an overflow, but the source buffer is constant, so we're not really interested in this case
// ok: raptor-unsafe-ret-snprintf-vsnprintf
int ret = snprintf(myname, 10, "0123456789");
char name2[5] = "1234";
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(0, 0, "My name is: %s", name2);
char *p = (char *)malloc(len);
snprintf(p, len, "My name is: %s", name2);
// prints 123
std::cout << p;
return 0;
}
char *f(const char *input)
{
char buf[128];
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(buf, 128, "%s", input);
char *out = malloc(len + 1);
// This isn't technically a vulnerability but it is suspicious:
// * `snprintf(...)` will not return `-1` because the format string is valid
// * `buf` will be NUL-terminated, because `128 > 0`
// * `strncpy(...)` will only copy `max(strlen(buf), len + 1)` characters
// * `strlen(buf)` is less than `len + 1`, so `out` will be NUL-terminated
strncpy(out, buf, len + 1);
// OOB read
memcpy(out, buf, len + 1);
return out;
}
char *non_string(const char *input, size_t n)
{
char buf[128];
// ok: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(buf, 128, "%u", n);
memcpy(out, buf, len + 1);
return out;
}
char *f(const char *input)
{
char buf[128];
// there is a length check below
// todook: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(buf, 128, "any_cmd '%s'", input);
if (len < 0 || len > 128 - 1)
{
return NULL;
}
char *out = malloc(len);
strncpy(out, buf, len);
return out;
}
char *f(const char *input)
{
char buf[128];
// there is a length check below
// todook: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(buf, 128, "any_cmd '%s'", input);
if (len >= sizeof(buf))
{
return NULL;
}
char *out = malloc(len);
strncpy(out, buf, len);
return out;
}
char *f(const char *input)
{
char buf[128];
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(buf, 128, "any_cmd '%s'", input);
snprintf(buf, 128 - len, "foo");
}
char *f(const char *input)
{
char buf[128];
// there is a length check below
// todook: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(buf, 128, "any_cmd '%s'", input);
if (sizeof(buf) <= len)
{
return NULL;
}
char *out = malloc(len);
strncpy(out, buf, len);
return out;
}
size_t f(const char *input)
{
char buf[128];
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(buf, 128, "input=%s", input);
return strnlen(buf, len);
}
size_t f()
{
char buf[128];
// ok: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(buf, 128, "foo");
return strnlen(buf, len);
}
size_t f(const char *input)
{
char buf[128];
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
int len = snprintf(buf, 128, "input=%s", input);
return strncasecmp(buf, "input=foo", len);
}
void f(const char *input)
{
char buf[128];
int len = 0;
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
len += snprintf(&buf[len], 128, "input=%s, input");
return &buf[len] - buf;
}
void wide_strings(const wchar_t *input)
{
wchar_t buf[128];
int len = 0;
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
len += snprintf(&buf[len], 128, "input=%ls, input");
return &buf[len] - buf;
}
static char *gen_text(const char *prefix, const char *sub_prefix, char *buf, size_t sz)
{
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
int x = snprintf(buf, sz, "%s-%s-", prefix, sub_prefix);
// This isn't sanitized because of the `sz - 1` on the RHS
for (; (size_t)x < sz - 1; x++)
buf[x] = *prefix;
buf[x++] = 'x';
buf[x] = '\0';
return buf;
}
static char *
int_to_roman(int number, const char *p)
{
int len;
// ruleid: raptor-unsafe-ret-snprintf-vsnprintf
len = snprintf(numstr, sizeof(numstr), "%s", p);
for (p = numstr; *p != '\0'; p++, --len)
{
foo();
}
for (p = numstr; *p != '\0'; p++, len--)
{
foo();
}
// TODO: `i < len` is a sanitizer so we can't match on it being used as a
// loop condition
for (; i < len;)
{
foo();
}
for (i = 0; i < len;)
{
foo();
}
for (; i < len; i++)
{
foo();
}
for (i = 0; i < len; i++)
{
foo();
}
for (int i = 0; i < len;)
{
foo();
}
for (int i = 0; i < len; i++)
{
foo();
}
for (int i = 0, j = 0; i < len; i++)
{
foo();
}
return result;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,48 @@
rules:
- id: raptor-unsafe-ret-snprintf-vsnprintf
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: HIGH
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-131: Incorrect Calculation of Buffer Size"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://lwn.net/Articles/507319/
- https://g.co/kgs/PCHQjJ
- https://dustri.org/b/playing-with-weggli.html
message: >-
The snprintf() and vsnprintf() functions return the total length of
the string they tried to create. Therefore, this return value can be
larger than the size of the destination buffer. If it is used
unsafely, e.g. as an index to write to the destination buffer, memory
corruption might occur.
severity: WARNING
languages:
- c
- cpp
# NOTE: for another approach that uses taint mode, refer to `cpp.lang.security.strings.snprintf-return-value-length.snprintf-return-value-length`.
patterns:
- pattern-either:
- pattern: $_ = $FUN($_, $_, $FMT, ...)
- pattern: $_ += $FUN($_, $_, $FMT, ...)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: snprintf
- pattern: vsnprintf
# swprintf and vswprintf return a negative value if n or more
# widechars were requested to be written, thus behaving more safely
- metavariable-regex:
metavariable: $FMT
# NOTE: some format string specifiers are not handled
regex: '(".*%l?s.*"|".*%S.*"|[a-zA-Z_][a-zA-Z0-9_]*)'
@@ -0,0 +1,61 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#define BUFSIZE 256
void copy_string1(char *string)
{
char buf[BUFSIZE];
size_t length;
// ruleid: raptor-unsafe-ret-strlcpy-strlcat
length = strlcpy(buf, string, BUFSIZE);
// use length to access buf, e.g. with strncat()
}
int copy_string2(const char *string)
{
char buf[BUFSIZE];
if (!string)
return -1;
// ok: raptor-unsafe-ret-strlcpy-strlcat
if (strlcpy(buf, string, BUFSIZE) >= BUFSIZE)
return -1; // truncation
// safely use buf here, knowing it is complete and null-terminated
return 0;
}
void append_string(char *string)
{
char buf[BUFSIZE];
size_t length;
// ruleid: raptor-unsafe-ret-strlcpy-strlcat
length = strlcat(buf, string, BUFSIZE);
// use length to access buf
}
void qualify_username(char *username)
{
char buf[1024];
size_t length;
// ruleid: raptor-unsafe-ret-strlcpy-strlcat
length = strlcpy(buf, username, sizeof(buf));
strncat(buf, "@127.0.0.1", sizeof(buf) - length);
// ...
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,46 @@
rules:
- id: raptor-unsafe-ret-strlcpy-strlcat
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- audit
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: HIGH
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-131: Incorrect Calculation of Buffer Size"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://lwn.net/Articles/507319/
- https://g.co/kgs/PCHQjJ
message: >-
The strlcpy() and strlcat() functions return the total length of the
string they tried to create. For strlcpy() that means the length of
the source string. For strlcat() that means the initial length of the
destination string plus the length of of the source string.
Therefore, this return value can be larger than the size of the
destination buffer. If it is used unsafely, e.g. as an index to write
to the destination buffer, memory corruption might occur.
severity: WARNING
languages:
- c
- cpp
patterns:
- pattern-either:
- pattern: $_ = $FUN(...)
- pattern: $_ += $FUN(...)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: strlcpy
- pattern: strlcat
- pattern: wcslcpy
- pattern: wcslcat
- pattern: _mbslcpy
- pattern: _mbslcat
@@ -0,0 +1,30 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
int get_length1(char *string)
{
short length;
// ruleid: raptor-unsafe-strlen
length = strlen(string);
return length;
}
int get_length2(char *string)
{
unsigned int length;
// ok: raptor-unsafe-strlen
length = strlen(string);
return length;
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,52 @@
rules:
- id: raptor-unsafe-strlen
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Other Security
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-190: Integer Overflow or Wraparound"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://github.com/struct/mms
message: >-
The software performs a calculation that can produce an integer
overflow or wraparound, when the logic assumes that the resulting
value will always be larger than the original value. This can
introduce other weaknesses when the calculation is used for resource
management or execution control. When influenced by the size of an
input it is often easier to overflow a short than an int.
severity: WARNING
languages:
- c
- cpp
patterns:
- pattern-either:
# signed and unsigned short
- pattern: (short $_) = $FUN(...)
- pattern: (short int $_) = $FUN(...)
- pattern: (unsigned short $_) = $FUN(...)
- pattern: (unsigned short int $_) = $FUN(...)
# signed int
# - pattern: (int $LEN) = $FUN(...);
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: strlen
- pattern: lstrlen
- pattern: strnlen
- pattern: wcslen
- pattern: wcsnlen
# - pattern: _mbslen
# - pattern: _mbstrlen
# - pattern: _mbsnlen
# - pattern: _mbstrnlen
@@ -0,0 +1,124 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <string.h>
#define BUFSIZE 256
void copy_string1(char *string)
{
char buf[BUFSIZE];
// ruleid: raptor-unterminated-string-strncpy
strncpy(buf, string, BUFSIZE);
}
void copy_string2(char *string)
{
char buf[BUFSIZE];
// ruleid: raptor-unterminated-string-strncpy
stpncpy(buf, string, BUFSIZE);
}
void copy_string3(char *string)
{
char buf[BUFSIZE];
// ok: raptor-unterminated-string-strncpy
strncpy(buf, string, BUFSIZE);
buf[BUFSIZE - 1] = '\0';
}
int test_func()
{
char longString[] = "String signifying nothing";
char shortString[16];
// ruleid: raptor-unterminated-string-strncpy
strncpy(shortString, longString, 16);
printf("The last character in shortString is: %c (%1$x)\n", shortString[15]);
return 0;
}
void test_func2(int argc, char **argv)
{
char Filename[256];
char Pattern[32];
// ...
// ruleid: raptor-unterminated-string-strncpy
strncpy(Filename, argv[1], sizeof(Filename));
// ruleid: raptor-unterminated-string-strncpy
strncpy(Pattern, argv[2], sizeof(Pattern));
printf("Searching file: %s for the pattern: %s\n", Filename, Pattern);
Scan_File(Filename, Pattern);
}
void authenticate(int sockfd)
{
char user[1024], *buffer;
size_t size;
int n, cmd;
cmd = read_integer(sockfd);
size = read_integer(sockfd);
if (size > MAX_PACKET)
return -1;
buffer = (char *)calloc(size + 1, sizeof(char));
if (!buffer)
return -1;
read_string(buffer, size);
switch (cmd)
{
case USERNAME:
// ruleid: raptor-unterminated-string-strncpy
strncpy(user, buffer, sizeof(user));
if (!is_username_valid(user))
goto fail;
break;
// ...
}
}
int process_email(char *email)
{
char buf[1024], *domain;
// ruleid: raptor-unterminated-string-strncpy
strncpy(buf, email, sizeof(buf));
domain = strchr(buf, '@');
if (!domain)
return -1;
*domain++ = '\0';
// ...
return 0;
}
int test()
{
char *hello = "HELLO WORLD";
char dest[10];
memset(dest, '\xAA', 10);
// ruleid: raptor-unterminated-string-strncpy
strncpy(dest, hello, 5);
// to print contents of `dest` in hex
for (int i = 0; i < 10; ++i)
printf("%hhx ", dest[i]);
printf("\n");
}
int main()
{
printf("Hello, World!");
return 0;
}
@@ -0,0 +1,56 @@
rules:
- id: raptor-unterminated-string-strncpy
metadata:
author: Marco Ivaldi <raptor@0xdeadbeef.info>
category: security
subcategory:
- vuln
vulnerability_class: Memory Issues
likelihood: MEDIUM
impact: MEDIUM
confidence: MEDIUM
technology:
- c
- cpp
cwe:
- "CWE-170: Improper Null Termination"
- "CWE-126: Buffer Over-read"
owasp:
- A10:2025 - Mishandling of Exceptional Conditions
references:
- https://g.co/kgs/PCHQjJ
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
message: >-
If there is no NUL character byte in the first n bytes of the source
string, strncpy() and stpncpy() do not NUL-terminate the destination
buffer. If the program does not explicitly terminate the destination
buffer, this will almost certainly result in information disclosure,
and possibly a buffer overflow condition.
severity: WARNING
languages:
- c
- cpp
# NOTE: other functions that do not `NUL`-terminate the destination buffer are not covered (e.g., `read`, `readlink`, `fread`, `memcpy`, etc.).
# NOTE: try to avoid false positives when `sizeof(dest) - 1` is used and in other similar cases.
patterns:
- pattern: $FUN(...)
- metavariable-pattern:
metavariable: $FUN
pattern-either:
- pattern: strncpy
- pattern: stpncpy
- pattern: wcsncpy
- pattern: wcpncpy
- pattern: _mbsncpy
- pattern-not-inside: |
$FUN($DST, $_, $_);
...
$DST[$_] = NULL;
- pattern-not-inside: |
$FUN($DST, $_, $_);
...
$DST[$_] = '\0';
- pattern-not-inside: |
$FUN($DST, $_, $_);
...
$DST[$_] = 0;
@@ -0,0 +1,360 @@
// Marco Ivaldi <raptor@0xdeadbeef.info>
#include <stdio.h>
#include <stdlib.h>
#define MEMSIZE 256
void alloc_and_free1()
{
int err = 1, bailout = 0;
char *ptr = (char *)malloc(MEMSIZE);
// this should be caught but it isn't, due to a documented limitation in semgrep
// https://semgrep.dev/docs/writing-rules/pattern-syntax/#ellipses-and-statement-blocks
// todoruleid: raptor-use-after-free
if (err)
{
bailout = 1;
free(ptr);
}
if (bailout)
fprintf(stderr, "error: %p\n", ptr);
free(ptr);
// ruleid: raptor-use-after-free
fprintf(stderr, "error: %p\n", ptr);
}
void alloc_and_free2()
{
char *ptr = (char *)malloc(MEMSIZE);
free(ptr);
ptr = (char *)malloc(MEMSIZE);
// ok: raptor-use-after-free
fprintf(stderr, "error: %p\n", ptr);
}
void uaf(int argc, char **argv)
{
char *buf1R1;
char *buf2R1;
char *buf2R2;
char *buf3R2;
buf1R1 = (char *)malloc(BUFSIZER1);
buf2R1 = (char *)malloc(BUFSIZER1);
free(buf2R1);
buf2R2 = (char *)malloc(BUFSIZER2);
buf3R2 = (char *)malloc(BUFSIZER2);
// ruleid: raptor-use-after-free
strncpy(buf2R1, argv[1], BUFSIZER1 - 1);
free(buf1R1);
free(buf2R2);
free(buf3R2);
}
// https://docs.microsoft.com/en-us/cpp/sanitizers/error-heap-use-after-free
int heap_use_after_free()
{
char *x = (char *)malloc(10 * sizeof(char));
free(x);
// ...
// ruleid: raptor-use-after-free
return x[5];
}
char test()
{
char *ptr = (char *)malloc(10 * sizeof(char));
free(ptr);
// ruleid: raptor-use-after-free
return *ptr;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct name
{
char *myname;
void (*func)(char *str);
} NAME;
void other_func(char *ignored) {}
void refreencode(char *ignored) {}
int bad_code1()
{
NAME *var;
char buf[10];
var = (NAME *)malloc(sizeof(struct name));
free(var);
// ruleid: raptor-use-after-free
strcpy(buf, (char *)var);
// ruleid: raptor-use-after-free
other_func((char *)(*var));
// ruleid: raptor-use-after-free
other_func((char *)var[0]);
// ruleid: raptor-use-after-free
var->func(var->myname);
return 0;
}
int bad_code2()
{
NAME *var;
char buf[10];
var = (NAME *)malloc(sizeof(struct name));
free(var);
// ruleid: raptor-use-after-free
strcpy(buf, (char *)*var);
// ruleid: raptor-use-after-free
other_func((char *)var);
// ruleid: raptor-use-after-free
other_func((char *)var->myname);
return 0;
}
int okay_code1()
{
NAME *var;
var = (NAME *)malloc(sizeof(struct name));
free(var);
var = NULL;
// This will segmentation fault
// ok: raptor-use-after-free
other_func((char *)var);
other_func((char *)var->myname);
other_func((char *)*var);
return 0;
}
int okay_code2()
{
NAME *var;
var = (NAME *)malloc(sizeof(struct name));
free(var);
var = NULL;
var = (NAME *)malloc(sizeof(struct name));
// ok: raptor-use-after-free
other_func((char *)var);
other_func((char *)var->myname);
other_func((char *)*var);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
typedef struct name
{
char *myname;
void (*func)(char *str);
} NAME;
void other_func(char *ignored) {}
int bad_code1()
{
NAME *var;
var = (NAME *)malloc(sizeof(struct name));
free(var);
// ruleid: raptor-use-after-free
var->func("use after free");
return 0;
}
int okay_code1()
{
NAME *var;
var = (NAME *)malloc(sizeof(struct name));
free(var);
var = NULL;
// This will segmentation fault
// ok: raptor-use-after-free
var->func("use after free");
return 0;
}
int bad_code2()
{
NAME *var;
var = (NAME *)malloc(sizeof(struct name));
free(var);
// ruleid: raptor-use-after-free
other_func(var->myname);
return 0;
}
int okay_code2()
{
NAME *var;
var = (NAME *)malloc(sizeof(struct name));
free(var);
var = NULL;
// This will segmentation fault
// ok: raptor-use-after-free
other_func(var->myname);
return 0;
}
struct NAME
{
char first_name[32];
int auth;
} s_auth;
int bad_code3()
{
struct NAME *var;
var = malloc(sizeof(s_auth));
free(var);
// ruleid: raptor-use-after-free
if (var->auth)
{
printf("you have logged in already");
}
else
{
printf("you do not have the permision to log in.");
}
return 0;
}
int ok_code3()
{
struct NAME *var;
var = malloc(sizeof(s_auth));
free(var);
var = NULL;
// ok: raptor-use-after-free
if (var->auth)
{
printf("you have logged in already");
}
else
{
printf("you do not have the permision to log in.");
}
return 0;
}
struct lv
{
int length;
char *value;
} lv;
struct lv2
{
int length;
struct lv *lv;
} lv2;
int bad_code4()
{
int initial = 1000;
struct lv *lv = malloc(sizeof(*lv));
lv->length = initial;
lv->value = malloc(initial);
free(lv);
// ruleid: raptor-use-after-free
free(lv->value);
return 0;
}
int ok_code4()
{
int initial = 1000;
struct lv *lv = malloc(sizeof(*lv));
lv->length = initial;
lv->value = malloc(initial);
// ok: raptor-use-after-free
free(lv->value);
// ok: raptor-use-after-free
free(lv);
return 0;
}
int bad_code5()
{
int initial = 1000;
struct lv *lv = malloc(sizeof(*lv));
lv->length = initial;
lv->value = malloc(initial);
struct lv2 *lv2 = malloc(sizeof(*lv2));
lv2->length = initial;
lv2->lv = lv;
// ok: raptor-use-after-free
free(lv2->lv);
// ruleid: raptor-use-after-free
free(lv2->lv->value);
// ok: raptor-use-after-free
free(lv2);
return 0;
}
int ok_code5()
{
int initial = 1000;
struct lv *lv = malloc(sizeof(*lv));
lv->length = initial;
lv->value = malloc(initial);
struct lv2 *lv2 = malloc(sizeof(*lv2));
lv2->length = initial;
lv2->lv = lv;
// ok: raptor-use-after-free
free(lv2->lv->value);
// ok: raptor-use-after-free
free(lv2->lv);
// ok: raptor-use-after-free
free(lv2);
return 0;
}
int bad_code6()
{
NAME *var;
var = (NAME *)malloc(sizeof(struct name));
free(var);
// ruleid: raptor-use-after-free
(*var).func("use after free");
return 0;
}
int ok_code6()
{
NAME *var;
var = (NAME *)malloc(sizeof(struct name));
free(var);
var = (NAME *)malloc(sizeof(struct name));
// ok: raptor-use-after-free
(*var).func("use after free");
return 0;
}
int bad_code7()
{
char *var;
char buf[10];
var = (char *)malloc(100);
free(var);
// ruleid: raptor-use-after-free
char buf[0] = var[0];
// ruleid: raptor-use-after-free
strcpy(buf, var);
return 0;
}
int main()
{
printf("Hello, World!");
return 0;
}
Loaded 100 of 473 files, more files were not shown because too many files have changed in this diff. Show more