agentleFS
nandhu-44nandhu-44/secure-vibe-coding/skills/secure-lowlevel/SKILL.md

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.

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
  1. Very specific:

    Always pass (pointer, length) pairs.

    line 22
  2. Very specific:

    Check before multiplying for allocation: if (n != 0 && size > SIZE_MAX / n) fail;, or use calloc(n, size), reallocarray, or …

    line 41
  3. Very specific:

    Use strtol/strtoul with errno = 0, end-pointer, and range checks.

    line 42
  4. Very specific:

    One owner per allocation: Document who frees. Free in exactly one place.

    line 46
  5. Very specific:

    Use a single-exit cleanup pattern (goto cleanup) so every error path frees exactly once:

    line 47
  6. Very specific:

    Don't keep pointers into a buffer that may be realloc'd, or into a container that may grow (iterator/reference invalidation in C++).

    line 61
  7. Very specific:

    Never return pointers or references to stack locals.

    line 62
  8. Distinctive:

    After moving from an object (C++), don't use it except to reassign or destroy.

    line 64
  9. Very specific:

    Check every return value: malloc, read/write (short reads!), snprintf, fclose, setuid, pthread_*.

    line 85
  10. Very specific:

    Run python3 ${CLAUDE_SKILL_DIR}/../secure-coding/scripts/secscan.py <changed files>.

    line 105

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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), alloca with unbounded size. Avoid strncpy (no NUL guarantee) and strncat (confusing size).
  • Use: snprintf(dst, sizeof dst, ...) and check its return (ret < 0 || (size_t)ret >= sizeof dst → truncated), strlcpy/strlcat where available, or memcpy after an explicit length check. Use fgets and getline.
  • Always pass (pointer, length) pairs. Never let a callee guess the buffer size. Use sizeof on arrays, not on pointers.
  • Parsing untrusted input (network packets, files): keep pos and len. Before every read, check need <= len - pos. That form avoids overflow, unlike pos + 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 + 1 for NUL-terminated strings. Loops use i < n, not i <= n.
  • C++: .at() in non-hot paths. std::array/std::vector instead of raw arrays. std::span for views. No operator[] 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 use calloc(n, size), reallocarray, or __builtin_mul_overflow / ckd_mul (C23).
  • Use strtol/strtoul with errno = 0, end-pointer, and range checks. Never atoi.
  • 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 NULL right after free.
  • 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/span outliving their owner.
  • C++: RAII everywhere (std::unique_ptr, std::vector, lock guards). No raw new/delete. Match new[]/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, or OPENSSL_cleanse. Plain memset before free is removed by the optimizer.
  • Compare MACs and tokens in constant time (CRYPTO_memcmp, sodium_memcmp). No memcmp/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 then open(). Open first, then fstat the fd. Use O_NOFOLLOW, O_CLOEXEC, O_EXCL|O_CREAT for new files, and openat relative to a trusted dir fd.
  • Temp files: mkstemp / tmpfile, never tmpnam/mktemp.
  • Processes: posix_spawn/execve with argv arrays. No system()/popen() with input. Drop privileges (setgid then setuid, 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,noexecstack

10. 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: unsafe rules, 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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.