Keras Model Custom Layer Detected at Model Run Time
Overview
Model ingestion issues commonly occur during basic serialization; however, Keras architectures heavily leverage custom Layer architectures evaluating raw Python logic directly executing prediction evaluations. PAIT-KERAS-301 alerts organizations utilizing Eresus Security static mapping logic that a specific model successfully delays suspicious operations directly bypassing load environments executing primarily during prediction invocation.
If a model is tagged with PAIT-KERAS-301 it specifies:
- Deployment formats align distinctly with
.kerasor native.h5specifications relying fundamentally on custom layer components distinctly categorized distinctly aside generalizedLambdalayers. - The procedural operations evaluated native mathematical formulas natively alongside undocumented environmental extraction patterns fundamentally processing local resources only strictly evaluating data input processing paths.
- While the deployment bypasses initialization vectors purely evaluated within PAIT-KERAS-100 logic, active execution inherently leverages unrestricted Python execution masking procedural hooks targeting backend operations natively.
Key Points
- Modern architecture commonly discourages extensive reliance actively parsing raw Python expressions directly dynamically. Attack operators construct custom configurations mimicking necessary activation bounds efficiently bridging directly into external payloads processing backend inference completely transparently natively masking attacks globally.
- Eresus Sentinel inherently dissects custom component initialization identifying anomalous system invocations entirely disconnected executing primarily inference paths avoiding static detection.
Impact
Fostering operations executing unverified routines dynamically actively enables system footprints capable natively executing moderate reconnaissance directly interacting explicitly bypassing traditional security networks entirely. This footprint potentially orchestrates gradual backend corruption specifically altering subsequent computation vectors seamlessly executing inference entirely compromised natively.
Best Practices
You should:
- Reconfigure models utilizing standard Keras component architectures completely avoiding unverified dynamic customization execution paths evaluating solely internal standard mathematically verified parameters universally.
- Continually process entire custom architectures analyzing operational logic completely within explicit structural analysis scanning comprehensively handled uniquely utilizing Eresus.
Remediation
Strictly quarantine specific custom execution configurations effectively immediately analyzing prediction environments comprehensively. Isolate models utilizing anomalous components heavily utilizing strict virtual hardware separation evaluating entirely execution patterns definitively extracting necessary model arrays efficiently safely bypassing native environmental operations reliably. If required, natively rewrite necessary mathematical operations exclusively strictly avoiding runtime Python evaluations actively.
Core assessment
A Keras artifact is not only weights. Files such as .keras and .h5 can carry custom layers, preprocessing code, and serialized configuration. When the model loads without error, teams often treat that as proof of safety. PAIT-KERAS-301 describes the opposite situation: suspicious logic is deferred until inference, so the artifact passes a load-time check and only reveals its behavior when a prediction is requested.
The finding should be treated as a code review problem. The model's accuracy is irrelevant to the security question. What matters is which Python objects the runtime will construct, which permissions those objects inherit, and whether the inference path can be exercised before the model reaches production.
Why this matters
- Custom layers run inside the inference service and inherit its environment variables, file access, and network reach.
- A load test that never calls prediction does not exercise the deferred path.
- Model registries, notebooks, and shared drives copy custom objects between teams, so one artifact can spread without a new download.
- Standard malware scanning is not designed to reason about serialized model code or framework-specific custom objects.
Practical example
A model loads cleanly in staging. On the first production request, a custom layer reads environment variables, writes a file, or opens an outbound connection. The request still returns a normal prediction, so the behavior is invisible unless process, file, and egress telemetry are reviewed together.
A second common case is a notebook that loads the model and runs one example input. The team sees a plausible answer and approves the artifact, but the example input never reaches the branch that contains the suspicious logic.
Common misconceptions
- "Safe mode blocks every code path." Safe mode restricts unsafe lambdas under specific conditions. It does not remove the need to review custom layer code that the application loads deliberately.
- "We tested one prediction." One input tests one path. Delayed logic can depend on metadata, environment, or request shape.
- "The model came from a trusted account." Trusted accounts are compromised, and legitimate models can be replaced after review.
Decision table
| Situation | Risk | What to do |
|---|---|---|
| Model is used for a local experiment | Bounded but unverified | Load it in a disposable environment and inspect custom objects |
| Model is served by a shared inference API | Lateral movement and data exposure | Quarantine it, review runtime telemetry, and restrict egress |
| Model is part of a regulated production flow | Compliance and contractual exposure | Treat it as a supply-chain incident and retest the intake gate |
Actionable checklist
- Enumerate every custom object, lambda, and preprocessing callback in the artifact before loading.
- Prefer explicit allowlists for custom layers instead of accepting arbitrary serialized classes.
- Load the artifact in a sandbox with no production credentials and no unrestricted network access.
- Review the code behind custom layers, including dependencies that the layer imports at runtime.
- Exercise prediction paths with edge inputs, not only the happy-path example.
- Pin the framework and loader versions so behavior does not change silently between environments.
- Record the artifact hash and the approval decision with the deployment.
- Rewrite or reject the model if the custom logic cannot be explained by its owner.
When to bring in external review
Bring in independent review when the organization cannot read the custom layer code, when the model is supplied by a third party, or when the inference service has access to sensitive data. The clearest signal is that nobody can explain what the custom object does without running it. Running unknown code to understand unknown code is not a review method.
How Eresus evaluates this
Eresus separates model behavior from runtime behavior. The review maps which objects are constructed, when they execute, what identities they inherit, and which evidence proves the behavior is reproducible. Findings are written for both engineers and decision makers, with a remediation path and a retest condition.
For teams that ship models, the review can also define an acceptance gate: allowed object types, required signature, sandbox requirements, and the exact evidence needed before production approval.
Review questions
- Which custom layers or callbacks does the artifact declare?
- Who reviewed the code inside those objects?
- Does the model load and predict in a sandbox with no credentials?
- Can the custom logic reach the network or the filesystem?
- Which identity and permissions does the inference worker use?
- Are framework and loader versions pinned and recorded?
- Do staging and production exercise the same prediction paths?
- Are process and egress logs retained for model workers?
- Is there a rollback artifact built from reviewed code?
- Does the intake policy allow arbitrary serialized objects?
FAQ
Does Keras safe mode stop a malicious custom layer?
No. Safe mode reduces risk from unsafe lambdas under specific conditions, but a custom layer that the application deliberately loads is still code. It must be reviewed, allowlisted, and run with least privilege.
Why did our scanner miss the behavior?
Many scanners inspect file structure or known signatures. Deferred logic that only runs during prediction may not appear until the model is exercised in a realistic environment.
Can the suspicious code run only in production?
Yes. It can depend on environment variables, request inputs, model metadata, or the presence of specific services. That is why sandbox testing should mirror production data flows without exposing production secrets.
What is the safest replacement?
Rebuild the model with standard layers, or have the owner document and sign the custom code. Then load it through an allowlist that rejects unapproved object types.
Remediation plan
1. Quarantine and inventory
Remove the artifact from shared stores, block its hash, and list every service, notebook, and pipeline that loaded it.
2. Reproduce safely
Run the model in an isolated environment with controlled inputs and full process, file, and network telemetry. Record exactly which layer executes and what it touches.
3. Replace the intake gate
Require an allowlist for custom objects, a signed artifact, and a sandboxed prediction test before any model reaches a production worker.
Reporting format
- State the finding, artifact hash, and the custom object involved.
- Identify the runtime identity, data class, and reachable systems.
- Provide reproducible evidence without unnecessary exploit detail.
- Separate model quality from security impact.
- Assign an owner and a retest criterion for every recommendation.
Related reading
- PAIT-KERAS-100: Keras model risks
- PAIT-KERAS-102: custom layer review
- AI supply chain attacks on Hugging Face
Next step
If your team serves third-party or custom-layer models, review the AI security service and Eresus Guard to add a sandboxed prediction test and an explicit object allowlist to the intake process.
AI Security Starter Training
Request a practical checklist for prompt injection, RAG data leakage, MCP risks, and model-file security before launch.
Related Research
Keras HDF5 Lambda Layer Arbitrary Code Execution
Identifies insecure legacy Keras objects (`.h5` or `.hdf5`) attempting to deserialize and execute malicious Python scripts hidden inside Lambda layer...
Deserialization ThreatsKeras Model Lambda Layer Suspicious Operator Detected at Model Load Time
High-severity deserialization threat identifying suspicious or highly uncharacteristic operational routines within a Keras Lambda layer payload upon...
Offensive SecurityAI Supply Chain Attacks: The Hidden Trojans Inside Open-Source LLMs
AI supply-chain security guide covering untrusted model files, Pickle and deserialization risk, model provenance, Safetensors, GGUF, sandboxing, and MLOps controls.
Related Services
Scope Estimator
Get a rough engagement size before the scoping call.
- What this depth covers
- Full coverage of the OWASP-family test plan for the in-scope targets: broken access control, injection, authn and authz flaws, business-logic abuse, findings with reproduction steps.
- What it does not cover
- Multi-week adversary emulation, physical and phishing vectors, custom exploit development, source-code review.
Indicative effort
~5 tester-days
Estimate only, not a quote. It scales with the three factors above and assumes the targets are reachable and test accounts are provided in the test window.