android-jni-security
БесплатноБез исполняемых скриптовНе проверенAudits, detects, and remediates Android JNI and native C/C++ boundary security vulnerabilities. Use this skill when reviewing, auditing, hardening, or…
от android★ 10 827 звёзд на GitHubОб этом скилле
This skill provides rules and code patterns to secure Android JNI boundaries. Follow these patterns to prevent buffer overflows, pinned memory leaks, and Time-of-Check to Time-of-Use (TOCTOU) file races. They also prevent hardcoded native secrets, cross-thread reference crashes, and unhandled pending JVM exceptions.
Glossary
- JNI (Java Native Interface): The platform bridge connecting ART bytecode in Kotlin or Java with C/C++
.solibraries. - JNIEnv: A thread-local pointer to the JNI function table passed as the first argument to every native method. A
JNIEnv*pointer must NEVER be shared or cached across threads. - JavaVM: The process-wide virtual machine pointer used to attach and detach native threads (
AttachCurrentThread,DetachCurrentThread). - Local reference: A thread-scoped reference (
jobject,jclass,jstring,jarray) valid only during the active native call. - Global reference: A cross-thread reference (
NewGlobalRef) that keeps a Java object reachable across threads and calls until freed withDeleteGlobalRef. - TOCTOU (Time-of-Check to Time-of-Use): A race condition when managed code checks a file path before C/C++ re-opens that path string. An attacker can swap the file or symlink before
fopenoropenruns. - Pending JVM exception state: The state after a JNI call throws a managed exception. Native code must not call most JNI functions while an exception is pending. Check
ExceptionCheck(), then free resources and return, or clear and handle the failure.
Limitations
- This skill covers JNI boundary validation, reference and thread lifecycles, and native secret handling.
- This skill doesn't cover binary obfuscation or decompilation of stripped third-party
.solibraries. - For
.sobinary hardening, suggest NDK visibility flags (-fvisibility=hidden,-Wl,--exclude-libs,ALL), symbol stripping, and the Play Integrity API.
Setup and dependencies
- Android NDK and CMake: Configure
externalNativeBuildwithcmakeinbuild.gradleorbuild.gradle.kts, and include<jni.h>in C/C++. Ask for user confirmation before modifying Gradle build files or rebuilding the project interactively. - Android SDK: Use
android.os.ParcelFileDescriptorandandroid.security.keystore.*(API 23+ for AES-GCM inAndroidKeyStore).
JNI boundary security logic and decisions
1. JNI parameter mapping and release requirements
When managing JNI reference lifetimes, UTF-8 strings, or thread attachment, follow JNI tips. Evaluate every parameter crossing the JNI boundary against its C/C++ release contract:
| JNI Type | C/C++ Acquisition API | Risk if Unchecked or Unreleased | Required Cleanup Action |
|---|---|---|---|
jbyteArray (copy) |
GetByteArrayRegion() |
Stack or heap buffer overflow if length exceeds destination | Validate GetArrayLength() and check ExceptionCheck() (no release call needed) |
jbyteArray (in-place) |
GetByteArrayElements() |
Heap pinning leak or out-of-memory (OOM) nullptr dereference |
Validate GetArrayLength(), check for nullptr, and call ReleaseByteArrayElements() on all paths |
jstring (input) |
GetStringUTFChars() |
Native UTF-8 buffer leak or OOM nullptr dereference |
Check for nullptr and call ReleaseStringUTFChars() before DeleteLocalRef() |
jstring (output) |
NewStringUTF() |
Runtime abort when raw native bytes are not valid Modified UTF-8 | Sanitize text to valid Modified UTF-8 first, or return jbyteArray for binary data |
jobject / jclass (local) |
GetObjectClass(), FindClass(), GetObjectField() |
Local reference exhaustion in loops and on attached threads | Call DeleteLocalRef() when finished, especially in loops or attached threads |
jobject / jclass (cached) |
NewGlobalRef() |
Dangling local pointer crash across calls or threads if not promoted | Promote with NewGlobalRef() and free with DeleteGlobalRef() on teardown |
2. Boundary input validation and buffer bounds logic
When passing untrusted inputs across JNI into C or C++ code, follow Use of native code. Validate array sizes in both managed wrappers and native C/C++ entry points before copying into fixed buffers:
IF (a Kotlin or Java class exposes a native method accepting arrays or
lengths) {
MUST declare the external (or native) method private.
MUST expose a public wrapper that validates non-empty inputs and enforces
maximum byte length bounds before calling JNI.
IN C/C++:
MUST verify array != nullptr and validate length > 0,
length <= kMaxBufferSize, and length <= env->GetArrayLength(array).
IF (bounds validation fails) {
MUST throw java/lang/IllegalArgumentException using
env->ThrowNew and return immediately before copying memory.
}
IF (copying bytes into a native buffer) {
MUST copy with `env->GetByteArra
Установить android-jni-security в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл android-jni-security?
Audits, detects, and remediates Android JNI and native C/C++ boundary security vulnerabilities. Use this skill when reviewing, auditing, hardening, or securing Android JNI boundaries, Kotlin external or Java native methods, and C/C++ shared libraries (System.loadLibrary) against buffer overflow, memory pinning, Time-of-Check to Time-of-Use (TOCTOU) file path races, hardcoded C++ cryptographic keys, cross-thread JNI reference and session callback lifecycles, or unhandled pending JVM exceptions and local reference leaks. Don't use for pure managed Kotlin or Java code without native JNI bindings or general reverse-engineering of stripped binaries.
Как установить скилл android-jni-security?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл android-jni-security запускает скрипты?
Нет, скилл состоит только из инструкций (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