Home / Market / android jni security

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 an

skill★ 108450 dlgithubApache-2.0Install in CosmosUpstream Source

Documentation & Preview

--- 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:

---

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

Limitations

Setup and dependencies

* * *

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.

object SecureNativeDataProcessor {

    private const val MAX_PACKET_SIZE = 2048

    in