native-memory-safety-and-ffi
БесплатноБез исполняемых скриптовНе проверенUse when the diff changes C, C++ or Objective-C, Rust unsafe blocks, Go unsafe or cgo, JNI, Python ctypes/cffi or C extensions, Swift unsafe pointers, C#…
от makifbaysal★ 123 звезды на GitHubОб этом скилле
Native Memory Safety and FFI
Overview
The hard exclusion on memory safety covers memory-safe languages. Native code is the opposite case: in C, C++, Objective-C, unsafe Rust, cgo, JNI and ctypes, one wrong length turns a packet, a save file, a mod, an image or a model file into a read or write outside the buffer. These bugs are in scope whenever untrusted bytes reach the code.
Core principle: re-derive every length, index and lifetime from the worst value the attacker can send — not from the value the tests use — and state the effect you can show (read, write, use-after-free, crash) without inflating it.
1. Who Sends the Bytes?
A finding needs a realistic untrusted source: a network peer, a file the user opens or downloads (save, replay, mod, asset, document, model), an IPC message from a less-trusted process, a plugin from a third party. A buffer bug reachable only from the program's own constant data, or from a developer's local CLI flag, is a bug, not a vulnerability.
2. Bounds (CWE-119, CWE-125, CWE-787)
// ❌ len comes from the packet; dst holds 64 bytes
uint16_t len = read_u16(pkt);
memcpy(dst, pkt->data, len);
// ✅ check against the destination AND what the source actually holds
if (len > sizeof(dst) || len > pkt->remaining) return ERR_MALFORMED;
memcpy(dst, pkt->data, len);
Check both sides of every copy. Recompute the room left after a header, a prefix, alignment padding or a terminator. strcpy, strcat, sprintf, gets and strncpy (no terminator when it truncates) on input are findings by shape; std::vector::operator[] and std::span do not check, .at() does.
3. Integer Arithmetic Before Allocation (CWE-190, CWE-191, CWE-681)
// ❌ both factors come from the wire: the 32-bit product wraps, the allocation is tiny,
// and the loop still writes count records of rec bytes
uint32_t count = r.u32(), rec = r.u32();
uint8_t* buf = (uint8_t*)malloc(count * rec);
for (uint32_t i = 0; i < count; ++i) r.read(buf + (size_t)i * rec, rec);
// ✅ upper bounds, then checked multiplication in size_t
size_t bytes;
if (count > kMaxRecords || rec > kMaxRecordSize ||
__builtin_mul_overflow((size_t)count, (size_t)rec, &bytes)) return Reject();
High-hit shapes: a - b where b > a can happen; a 64-bit length narrowed to int or uint16_t; a signed length that is negative passed as size_t; -1 as a sentinel that becomes SIZE_MAX; an addition near the type's maximum. Rust: checked_mul/checked_add, or try_into() instead of as for narrowing.
4. Units (CWE-131)
Bytes vs elements vs UTF-16 code units vs pages; sizeof(ptr) where sizeof(*ptr) was meant; a length validated in one unit and used in another. A bounds check that uses the same wrong unit as the allocation is still wrong.
5. Lifetimes (CWE-416, CWE-415, CWE-825)
- A callback, timer, completion handler or observer that fires after its owner was freed — look at every error, cancel and close path.
- Iterator invalidation:
push_back/eraseon a container while iterating it; a reference into a vector kept across a resize. c_str()orstd::string_viewof a temporary; a pointer into a buffer that is reallocated.- Double free on an error path that frees and then falls through to common cleanup.
- Rust
unsafe:slice::from_raw_parts(ptr, len)withlenfrom input,get_unchecked,set_lenbefore initialization,transmutebetween unrelated types, a hand-writtenunsafe impl Send/Sync.
6. Uninitialized and Type-Confused Memory (CWE-457, CWE-843)
- A struct or buffer with padding or unwritten fields sent over the network, written to a file or hashed — it leaks stack or heap contents to a peer.
- A downcast chosen by a tag from the wire (
static_cast<Derived*>(base)afterif (msg.kind == …)) where the object's real type was never checked; a union read through the wrong member.
7. Format Strings (CWE-134)
printf(user), syslog(LOG_INFO, user), NSLog(user), String(format: user) — a fixed format with the input as an argument is the fix.
8. FFI and ABI Boundaries
- Ownership: caller and callee disagree on who frees a buffer, or how long a pointer stays valid; a callback keeps a pointer to a Go, Java or Python object after the runtime moved or freed it.
- cgo: passing Go memory that contains Go pointers to C, or keeping a Go pointer in C after the call returns (both break the cgo pointer rules);
unsafe.Slice/unsafe.Stringover a C buffer with a length from input. - JNI and ctypes:
GetByteArrayElements/GetStringUTFCharswithout the matching release; ctypes calls with noargtypes/restype, so 64-bit pointers are truncated toint. - Layout: a struct declared differently on the two sides (packing, alignment, enum width), or a length passed in bytes where the other side expects elements.
- Unwinding: a Rust panic or C++ exception crossing an
extern "C"boundary.
9. Library and Plugin Loading (CWE-426, CWE-427)
A
Установить native-memory-safety-and-ffi в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл native-memory-safety-and-ffi?
Use when the diff changes C, C++ or Objective-C, Rust unsafe blocks, Go unsafe or cgo, JNI, Python ctypes/cffi or C extensions, Swift unsafe pointers, C# unsafe or Marshal code, or a native plugin, parser or loader that sees untrusted bytes - bounds, integer overflow before allocation, unit confusion, lifetimes, uninitialized memory, format strings, FFI ownership and library search order
Как установить скилл native-memory-safety-and-ffi?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл native-memory-safety-and-ffi запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic