secure-lowlevel
Skill0 starsChanged 15 days agoApache-2.0View on GitHub
Memory-safe and exploit-resistant patterns for low-level code. Use when writing or editing C, C++, Objective-C, Rust unsafe/FFI, Go cgo/unsafe, Zig, embedded/firmware, kernel modules, parsers, network protocol handlers, file-format decoders, or any code using pointers, buffers, manual memory management, length fields, or system calls. Prevents buffer overflows, out-of-bounds reads, integer overflow, use-after-free, double free, format-string bugs, uninitialized memory, TOCTOU races, compiler-removed secret wiping, and missing hardening flags.
In this repository6 other files it gives its agents.
- dist/AGENTS.mdAGENTS.md
- secure-ai-featuresSkill
- secure-codingSkill
- secure-reviewSkill
- secure-supply-chain-infraSkill
- secure-webSkill
The file
We split this skill into the rules it gives an agent
10 rules. About 0 are common, 1 is distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 22
Always pass (pointer, length) pairs.
- Very specific: line 41
Check before multiplying for allocation: if (n != 0 && size > SIZE_MAX / n) fail;, or use calloc(n, size), reallocarray, or …
- Very specific: line 42
Use strtol/strtoul with errno = 0, end-pointer, and range checks.
- Very specific: line 46
One owner per allocation: Document who frees. Free in exactly one place.
- Very specific: line 47
Use a single-exit cleanup pattern (goto cleanup) so every error path frees exactly once:
- Very specific: line 61
Don't keep pointers into a buffer that may be realloc'd, or into a container that may grow (iterator/reference invalidation in C++).
- Very specific: line 62
Never return pointers or references to stack locals.
- Distinctive: line 64
After moving from an object (C++), don't use it except to reassign or destroy.
- Very specific: line 85
Check every return value: malloc, read/write (short reads!), snprintf, fclose, setuid, pthread_*.
- Very specific: line 105
Run python3 ${CLAUDE_SKILL_DIR}/../secure-coding/scripts/secscan.py <changed files>.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Secure Low-Level Code
Memory-safety bugs dominate real-world agent failures. On SecureAgentBench (OSS-Fuzz C/C++ projects; Chen et al., SecureAgentBench, arXiv:2509.22097), over 80% of functionally correct agent patches for CWE-120 still contained the overflow. Newly introduced bugs were mostly double free (CWE-415), use-after-free (CWE-416), compiler-removed buffer clearing (CWE-14), unchecked copies (CWE-120), and out-of-bounds reads. The rules below target exactly these.
0. Prefer a memory-safe option when you have the choice
For new components, prefer Rust, Go, or a managed language (see CISA/NSA, The Case for Memory Safe Roadmaps, 2023). In existing C/C++, use the safest local idioms: C++ containers, std::span, std::string_view with lifetime care, smart pointers. Don't rewrite unasked.
1. Bounds: every write and read has a proven size [CWE-120, 121, 122, 125, 787]
- Banned:
gets,strcpy,strcat,sprintf,vsprintf,scanf("%s"),strtok(not reentrant),allocawith unbounded size. Avoidstrncpy(no NUL guarantee) andstrncat(confusing size). - Use:
snprintf(dst, sizeof dst, ...)and check its return (ret < 0 || (size_t)ret >= sizeof dst→ truncated),strlcpy/strlcatwhere available, ormemcpyafter an explicit length check. Usefgetsandgetline. - Always pass (pointer, length) pairs. Never let a callee guess the buffer size. Use
sizeofon arrays, not on pointers. - Parsing untrusted input (network packets, files): keep
posandlen. Before every read, checkneed <= len - pos. That form avoids overflow, unlikepos + need <= len./* ✅ length-prefixed field reader */ static int read_field(const uint8_t *buf, size_t len, size_t *pos, uint8_t *out, size_t out_cap, size_t *out_len) { if (len - *pos < 2) return -1; /* room for the length header? */ size_t n = ((size_t)buf[*pos] << 8) | buf[*pos + 1]; *pos += 2; if (n > len - *pos || n > out_cap) return -1; /* claimed length must fit both input and output */ memcpy(out, buf + *pos, n); *pos += n; *out_len = n; return 0; } - Off-by-one: allocate
len + 1for NUL-terminated strings. Loops usei < n, noti <= n. - C++:
.at()in non-hot paths.std::array/std::vectorinstead of raw arrays.std::spanfor views. Nooperator[]with unchecked external indices.
2. Integers [CWE-190, 191, 681, 194]
- Sizes are
size_t. Never compare signed and unsigned. Reject negative lengths before converting. - Check before multiplying for allocation:
if (n != 0 && size > SIZE_MAX / n) fail;, or usecalloc(n, size),reallocarray, or__builtin_mul_overflow/ckd_mul(C23). - Use
strtol/strtoulwitherrno = 0, end-pointer, and range checks. Neveratoi. - Watch implicit truncation (
size_t→int,uint32_t→uint16_t) on length fields.
3. Lifetime & ownership [CWE-415, 416, 401, 762, 825]
- One owner per allocation. Document who frees. Free in exactly one place. Set the pointer to
NULLright afterfree. - Use a single-exit cleanup pattern (
goto cleanup) so every error path frees exactly once:int process(const char *path) { int rc = -1; FILE *f = NULL; char *buf = NULL; if (!(f = fopen(path, "rb"))) goto cleanup; if (!(buf = malloc(BUF_SZ))) goto cleanup; /* ... */ rc = 0; cleanup: free(buf); if (f) fclose(f); return rc; } - Don't keep pointers into a buffer that may be
realloc'd, or into a container that may grow (iterator/reference invalidation in C++). - Never return pointers or references to stack locals. Watch
std::string_view/spanoutliving their owner. - C++: RAII everywhere (
std::unique_ptr,std::vector, lock guards). No rawnew/delete. Matchnew[]/delete[]. Rule of 0/3/5. - After moving from an object (C++), don't use it except to reassign or destroy.
4. Initialization [CWE-457, 908, 665]
Initialize every variable at declaration (= {0}, = {}). Check malloc for NULL and zero it (calloc) if any field may be read before writing. Compile with -ftrivial-auto-var-init=zero where supported.
5. Format strings & variadics [CWE-134]
A format string is always a literal: printf("%s", msg), syslog(LOG_ERR, "%s", msg). Enable -Wformat=2 -Werror=format-security. Annotate wrappers with __attribute__((format(printf, N, M))).
6. Secrets in memory [CWE-14, 226, 244]
- Wipe keys and passwords with
explicit_bzero(glibc/BSD),memset_s(C11 Annex K),SecureZeroMemory(Windows),sodium_memzero, orOPENSSL_cleanse. Plainmemsetbeforefreeis removed by the optimizer. - Compare MACs and tokens in constant time (
CRYPTO_memcmp,sodium_memcmp). Nomemcmp/early-exit loops on secrets. Avoid secret-dependent branches and table indices in crypto code. - Lock sensitive pages if needed (
mlock) and avoid core dumps of secrets (prctl(PR_SET_DUMPABLE, 0)).
7. Files, processes, races [CWE-367, 377, 78, 59]
- TOCTOU: don't
access()/stat()and thenopen(). Open first, thenfstatthe fd. UseO_NOFOLLOW,O_CLOEXEC,O_EXCL|O_CREATfor new files, andopenatrelative to a trusted dir fd. - Temp files:
mkstemp/tmpfile, nevertmpnam/mktemp. - Processes:
posix_spawn/execvewith argv arrays. Nosystem()/popen()with input. Drop privileges (setgidthensetuid, check returns). Sanitize the environment. - Threads: protect shared state with mutexes or atomics. Data races are UB.
- Signal handlers: only async-signal-safe functions.
8. Error handling [CWE-252, 253, 754]
Check every return value: malloc, read/write (short reads!), snprintf, fclose, setuid, pthread_*. Mark functions [[nodiscard]] / __attribute__((warn_unused_result)).
9. Build hardening (always add to new build files)
See hardening-flags.md. Minimum for GCC/Clang:
-O2 -Wall -Wextra -Wformat=2 -Wconversion -Wsign-conversion -Werror=format-security -Werror=implicit
-D_FORTIFY_SOURCE=3 -D_GLIBCXX_ASSERTIONS -fstack-protector-strong -fstack-clash-protection
-fcf-protection=full (x86) / -mbranch-protection=standard (arm64) -fPIE -pie -Wl,-z,relro,-z,now -Wl,-z,noexecstack10. Verify: sanitizers & fuzzing
For parsers and anything touching untrusted bytes, add a test build with -fsanitize=address,undefined and a libFuzzer/AFL++ harness. See sanitizers-fuzzing.md. If you can, compile and run the tests with ASan before replying.
Language-specific references
- c-cpp.md: CERT rules digest, safe replacements table, C++ idioms
- rust-unsafe.md:
unsaferules, FFI,SAFETY:comments, Miri - go-unsafe-cgo.md:
unsafe.Pointer, cgo, slices and integer conversions - embedded.md: firmware, MCU, no-heap patterns, secure boot, debug ports
Before you reply
Run python3 ${CLAUDE_SKILL_DIR}/../secure-coding/scripts/secscan.py <changed files>. Walk the C/C++ section of self-review.md. Compile with warnings (and ASan if possible). State the bounds and ownership assumptions in 1–2 lines.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

