# Java Memory/Native Layer Risk Detection Module

> Memory operations, native code, low-level API security risks

## Overview

Java memory and native layer operations bypass the JVM Security Manager, which can lead to serious security issues including memory corruption, privilege escalation, and DoS.

**Medium-High Level Risks**:

- sun.misc.Unsafe direct memory operations
- ByteBuffer Direct Memory off-heap memory leaks
- GraalVM Native Image security boundaries
- JNA dynamic library loading

---

## 1. sun.misc.Unsafe Risks

### Dangerous Patterns

```java
// ❌ High: Unsafe direct memory operations
import sun.misc.Unsafe;
import java.lang.reflect.Field;

Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);

// Dangerous operations
long address = unsafe.allocateMemory(1024);  // Off-heap memory, not managed by GC
unsafe.putLong(address, 0x4141414141414141L);  // Arbitrary memory write
unsafe.freeMemory(address);  // Forgetting to free -> memory leak

// Even more dangerous: modifying object fields to bypass access control
Object obj = new SecureObject();
Field secretField = SecureObject.class.getDeclaredField("secret");
long offset = unsafe.objectFieldOffset(secretField);
unsafe.putObject(obj, offset, "hacked");  // Bypasses private/final
```

### Detection Rules

```bash
grep -rn "sun\.misc\.Unsafe\|jdk\.internal\.misc\.Unsafe" --include="*.java" -A 5
grep -rn "\.allocateMemory\|\.freeMemory\|\.putLong\|\.getLong" --include="*.java" -B 5
grep -rn "objectFieldOffset" --include="*.java" -A 3
```

### Security Recommendations

- ✅ **Avoid using Unsafe**; use Java standard APIs
- ✅ If necessary, restrict to trusted code paths
- ✅ Use `VarHandle` (Java 9+) as a replacement for Unsafe
- ✅ Properly manage allocateMemory/freeMemory pairing

---

## 2. ByteBuffer Direct Memory Leak

### Dangerous Patterns

```java
// ❌ Medium: Direct ByteBuffer memory leak
ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 100);  // 100MB off-heap memory
// Use buffer...
// Forgetting to explicitly free, relying on GC -> OOM

// ❌ Loop allocation of Direct Buffers
for (int i = 0; i < 10000; i++) {
    ByteBuffer buf = ByteBuffer.allocateDirect(1024 * 1024);  // 10MB each time
    process(buf);  // Exhausts process memory before Full GC
}
```

### Detection Rules

```bash
grep -rn "ByteBuffer\.allocateDirect" --include="*.java" -A 5
grep -rn "MappedByteBuffer" --include="*.java" -A 3
```

### Security Recommendations

- ✅ Monitor Direct Memory usage (`-XX:MaxDirectMemorySize`)
- ✅ Reuse ByteBuffer object pools
- ✅ Explicitly call `((DirectBuffer)buffer).cleaner().clean()`
- ✅ Use try-with-resources to manage NIO resources

---

## 3. GraalVM Native Image Security Boundaries

### Risk Points

```java
// ❌ Medium: Improper reflection configuration exposes internal classes
// reflect-config.json
{
  "name": "com.example.InternalService",
  "allDeclaredMethods": true,  // Overly permissive
  "allDeclaredFields": true
}

// ❌ JNI configuration exposes native methods
// jni-config.json
{
  "name": "com.example.NativeLib",
  "methods": [{"name": "executeCommand"}]  // Dangerous native method
}
```

### Detection Rules

```bash
grep -rn "allDeclaredMethods.*true\|allDeclaredFields.*true" --include="*-config.json"
grep -A 5 "jni-config.json" . 2>/dev/null
```

### Security Recommendations

- ✅ Minimize reflection/JNI configuration
- ✅ Whitelist specific methods instead of `allDeclared*`
- ✅ Audit native-image configuration files

---

## 4. JNA Dynamic Library Loading

### Dangerous Patterns

```java
// ❌ High: User-controlled library path
import com.sun.jna.Native;

String libPath = request.getParameter("lib");  // User input
Native.load(libPath, MyLibrary.class);  // Load arbitrary .so/.dll -> RCE

// ❌ Medium: Unvalidated native method calls
public interface CLib extends Library {
    int system(String cmd);  // Directly exposes system()
}

CLib clib = Native.load("c", CLib.class);
String cmd = request.getParameter("cmd");
clib.system(cmd);  // Command injection
```

### Detection Rules

```bash
grep -rn "Native\.load\|NativeLibrary\.getInstance" --include="*.java" -A 5
grep -rn "extends Library" --include="*.java" -A 10 | grep "system\|exec"
```

### Security Recommendations

- ✅ **Never** allow user-controlled library names or paths
- ✅ Whitelist allowed native libraries
- ✅ Validate native method call parameters
- ✅ Restrict the scope of exposed native methods

---

## Comprehensive Detection Checklist

### High Risk

- [ ] Unsafe direct memory operations
- [ ] JNA user-controlled library loading
- [ ] JNA exposing system/exec native methods

### Medium Risk

- [ ] Large Direct ByteBuffer allocations without explicit free
- [ ] GraalVM allDeclared* configuration overly permissive
- [ ] MappedByteBuffer not properly unmapped

---

## Minimal PoC Examples
```bash
# JNA arbitrary library loading
rg -n "Native\\.load" --glob "*.{java,kt}"

# Unsafe usage
rg -n "sun\\.misc\\.Unsafe|Unsafe" --glob "*.{java,kt}"

# ByteBuffer large allocations
rg -n "allocateDirect\\(" --glob "*.{java,kt}"
```

---

## False Positives

- ✅ Unsafe used by trusted libraries for performance optimization (e.g., Netty)
- ✅ Direct ByteBuffer under pool management
- ✅ JNA loading system standard libraries (e.g., libc) with safe methods

---

## References

- JEP 193: Variable Handles (Unsafe replacement)
- JNA Security Best Practices
- GraalVM Native Image Security Guide
