SkillAgentSearch skills...

android-jni-security

Audits, detects, and remediates Android JNI and native C/C++ boundary

Install / Use

npx skills add android/skills --skill android-jni-security

Installs into whichever agent you are using.

About this skill
📄

SKILL.md

Installable skill definition

Quality Score

93/100

Category

Security

Supported Platforms

Universal

Our assessment of android-jni-security

android-jni-security scores 93/100 on our quality scale, 351st of 1,103 Security skills we index (top 32%).

Its SKILL.md is 30 KB long, well organised into 18 sections with 8 code examples: a thorough specification that gives an agent plenty to work with.

With 7,514 GitHub stars, it is one of the more widely adopted skills in the catalogue.

Substance
30/30
Structure
20/20
Description
12/15
Adoption
16/20
Freshness
15/15

Maintenance, license and trust

  • The repository was last updated about 2 months ago, so android-jni-security is actively maintained.
  • It is released under the Apache-2.0 license, a permissive license that allows use, modification and commercial use with attribution.
  • Its trust signals score 100/100, with no cautions. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.

android-jni-security compared with similar skills

All 4 of these similar skills score higher than android-jni-security; compare them before choosing.

SkillScoreStarsUpdatedFormat
android-jni-security (this skill)by android937.5k2mo agoSKILL.md
algorithmic-artby anthropics100177.9k2mo agoSKILL.md
pptxby anthropics100177.9k2mo agoSKILL.md
prospectingby coreyhaines3110062.2k5d agoSKILL.md
ad-creativeby coreyhaines3110062.2k5d agoSKILL.md

Frequently asked questions

How do I install android-jni-security?
Run npx skills add android/skills --skill android-jni-security. The install tabs above show the steps for each supported agent.
Which AI agents does android-jni-security work with?
It is written for Universal, as a SKILL.md file. Other agents that read the same format can often use it too.
Is android-jni-security safe to use?
It is Apache-2.0-licensed and scores 100/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
Is android-jni-security still maintained?
The repository was last updated about 2 months ago, so android-jni-security is actively maintained.

name: android-jni-security description: 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. license: Complete terms in LICENSE.txt metadata: author: Google LLC last-updated: '2026-11-19' keywords:

  • recipe
  • Android
  • Security
  • JNI
  • NDK
  • Native
  • C++
  • System.loadLibrary
  • GetByteArrayRegion
  • GetByteArrayElements
  • ReleaseByteArrayElements
  • ParcelFileDescriptor
  • TOCTOU
  • AndroidKeyStore
  • memset_explicit
  • NewGlobalRef
  • DeleteGlobalRef
  • AttachCurrentThread
  • ExceptionCheck

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++ .so libraries.
  • 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 with DeleteGlobalRef.
  • 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 fopen or open runs.
  • 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 .so libraries.
  • For .so binary 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 externalNativeBuild with cmake in build.gradle or build.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.ParcelFileDescriptor and android.security.keystore.* (API 23+ for AES-GCM in AndroidKeyStore).

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->GetByteArrayRegion(array, 0, length, buf) and check env->ExceptionCheck(). } IF (accessing or mutating elements in place) { MUST check that env->GetByteArrayElements(array, nullptr) returns a non-null pointer. MUST call env->ReleaseByteArrayElements(array, ptr, mode) (0 to copy back changes, or JNI_ABORT for read-only access) on every return path. } }

IF (native code accesses a direct ByteBuffer or constructs jstring output) { MUST verify env->GetDirectBufferAddress(buf) != nullptr and validate byte offsets against env->GetDirectBufferCapacity(buf). NEVER pass raw file or network bytes directly to env->NewStringUTF(). MUST sanitize text bytes to valid Modified UTF-8 before NewStringUTF(), or return a jbyteArray for arbitrary binary data. }

3. TOCTOU-safe file access across JNI

Never pass raw file path strings across JNI after checking file properties in Kotlin or Java:

IF (native C/C++ code reads or writes an application or shared file) { NEVER pass a raw file path String (jstring) across JNI to fopen() or open(). MUST canonicalize app-internal paths inside context.filesDir and open a ParcelFileDescriptor with the narrowest required mode (for example MODE_READ_ONLY). For content:// URIs, open the descriptor through context.contentResolver.openFileDescriptor(uri, "r"). MUST pass only the integer descriptor (pfd.fd) across JNI (jint fd) inside .use { ... }, and perform I/O on fd in C/C++ (pread or read). NEVER call close(fd), pass fd directly to fdopen(), or retain fd after .use { ... } returns because ParcelFileDescriptor owns it. Call dup(fd) if native code needs an owned descriptor copy. }

4. Cryptographic keys and native memory scrubbing

When storing or deriving cryptographic keys in Android apps, follow Hardcoded cryptographic secrets. Never embed static cryptographic keys or salts in C/C++ source files:

IF (an application encrypts, decrypts, or authenticates payloads across JNI) { NEVER hardcode secret keys, passwords, or salts in C/C++ arrays or string literals. MUST generate and store master keys in AndroidKeyStore (KeyStore.getInstance("AndroidKeyStore")) and run Cipher operations in Kotlin or Java. IF (native C/C++ cryptographic processing is required) { MUST pass only a short-lived, unwrapped per-session data encryption key for that single call rather than embedding a static key. } MUST overwrite transient sensitive native buffers before freeing memory using a volatile byte loop (volatile uint8_t*), or memset_explicit when minSdk is 34 or higher. MUST copy sensitive JNI byte arrays with GetByteArrayRegion into an owned buffer that you zero, or unpin GetByteArrayElements pointers with ReleaseByteArrayElements(..., JNI_ABORT). }

5. Cross-thread reference lifecycles and pending JVM exceptions

Never share JNIEnv* or local references across threads. Check for pending JVM exceptions after every JNI call:

IF (native code caches a callback object or invokes JNI from a background thread) { NEVER store a raw local jobject, jclass, or JNIEnv* in a static or global C/C++ variable. MUST cache JavaVM* (via JNI_OnLoad or env->GetJavaVM) and promote cached objects with env->NewGlobalRef(obj). MUST guard shared global references with a mutex and acquire a NewLocalRef under the lock before calling out, or stop worker threads before calling env->DeleteGlobalRef(globalRef). ON A NATIVE BACKGROUND THREAD: MUST check gJavaVm->GetEnv(..., JNI_VERSION_1_6) if the helper may run on an already-attached thread; call AttachCurrentThread only on JNI_EDETACHED, and call DetachCurrentThread only if this code attached the thread. MUST resolve app classes via GetObjectClass on a cached instance or a global jclass cached in JNI_OnLoad, because FindClass on a natively attached thread uses the system class loader. MUST delete local references (DeleteLocalRef), log and clear pending exceptions (ExceptionDescribe() then ExceptionClear()), and detach if attached by this call. }

IF (native code calls FindClass, GetMethodID, GetFieldID, Call*Method, GetObjectField, or GetStringUTFChars) { NEVER let C++ exceptions cross a JNIEXPORT boundary; catch them in C++ and translate them with env->ThrowNew(). MUST check env->ExceptionCheck() and null returns after EACH call before invoking the next JNI function. IF (env->ExceptionCheck() is true in a Kotlin or Java JNI entry point) { MUST release acquired native buffers and local references, then return immediately so the exception propagates; call ExceptionClear() only when native code handles the failure itself. } MUST annotate JNI-referenced Kotlin or Java members with @Keep (or add -keepclassmembers R8 rules). This prevents release shrinking from causing NoSuchMethodError or NoSuchFieldError. MUST call env->DeleteLocalRef on temporary local object, class, and string references before returning. }


Code and configuration patterns

Pattern 1: Kotlin wrapper validation and C++ bounds-checked region copy

Declare external methods private and validate sizes in a public Kotlin wrapper. Re-verify GetArrayLength in C++ and copy read-only bytes with GetByteArrayRegion so the managed array is never pinned. Keep C++ JNI symbol names aligned with the Kotlin external fun names, or the first call throws UnsatisfiedLinkError.

  • Expected Inputs: A non-empty ByteArray within the maximum frame size.
  • Expected Outputs: Validates bounds, copies into a native buffer with GetByteArrayRegion, and throws IllegalArgumentException on invalid sizes.
object SecureNativeDataProcessor {

    private const val MAX_PACKET_SIZE = 2048

    in

Truncated for display — read the full file on GitHub.

Related Skills

View on GitHub
GitHub Stars7.5k
CategorySecurity
Updated2mo ago
Forks488

Languages

Python

Trust signals

100/100

From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.

No cautions