Skip to content
ImagineWorld

Model Tampering with Trojan Horses and Model Reprogramming

node_idnode-book_adversarial-ai-defense-strategies_chapter-05-model-tampering-with-trojan-horses-and-model-reprogramming
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleModel Tampering with Trojan Horses and Model Reprogramming
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Model Tampering with Trojan Horses and Model Reprogramming

Section titled “Chapter 5 — Model Tampering with Trojan Horses and Model Reprogramming”

In the previous chapter, we looked at poisoning attacks and how subtle changes in the training data can affect the model’s integrity, enabling attackers to create backdoors triggered at inference time.

This chapter will look at more aggressive approaches to tampering with a model and creating backdoors, not by changing the data but by embedding small functionalities into the model. This is a Trojan horse approach to degrading model performance. It can also be used to hijack and repurpose a model, allowing attackers to use it for unintended functionality. We will look at model reprogramming attacks, too. These are more advanced techniques to hijack a model. We have already discussed pickles and the dangers they bring with traditional malicious code execution to exfiltrate data or spread malware.

This chapter will look at how pickle serialization can be exploited to deliver backdoors and with Trojan horses. We will also look at how attackers can achieve these objectives by tampering with models directly without manipulating pickle serialization. This will include reconstructing the model to append malicious layers acting as the Trojan horse. We will also look at the additional risks hosting AI models in mobile devices (edge AI) brings and how to mitigate them.

At the end of this chapter, we will have covered the following topics:

  • Injecting backdoors using pickle serialization
  • Injecting Trojan horses with Keras Lambda layers
  • Trojan horses with custom layers
  • Neural payload injections
  • Attacking edge AI
  • Model hijacking

We will start with a simple example of using pickle model serialization to inject a backdoor and achieve results similar to those of model poisoning.

Injecting backdoors using pickle serialization

Section titled “Injecting backdoors using pickle serialization”

We talked about pickle serialization and the dangers it brings to malicious code execution in Chapter 3. In this section, we will examine how it can be used to inject a backdoor. We will see a simple hands-on approach of how to inject malicious code into a model stored using the pickle format.

We will use a scenario where the attacker cannot rely on data poisoning. This can be for several reasons, such as lack of access to data, or the team may have recently implemented a good suite of data anomaly detection.

Similarly, they may have easier access to the deployed model, which they can alter without detection or take advantage of a team’s decision to move to the pickle format.

Pickle is known for its vulnerabilities, and Keras – among others—recommends against using it. Nevertheless, it remains a popular choice. Let’s assume the ImReCs team is also developing other models using PyTorch and scikit-learn. They have decided to move to using pickle serialization so that they can access them across frameworks.

Important note

We will walk through how to convert the model to a pickle format and how to then exploit pickle serialization to inject a backdoor.

They have migrated the CIFAR-10 CNN we have been using to a pickle file as follows:

from tensorflow.keras.models import load_model
import pickle
import numpy as np
# Step 1: Load the Keras model from the .h5 file
h5_file_path = "models/simple-cifar10.h5"
model = load_model(h5_file_path)
# Step 2: Save the loaded model as a .pkl file
pkl_file_path = "models/simple-cifar10.pkl"
with open(pkl_file_path, 'wb') as f:
pickle.dump(model, f)
# Step 3: Load the model back from the .pkl file
with open(pkl_file_path, 'rb') as f:
loaded_model = Pickle.load(f)
# Step 4: Make a prediction using the loaded model to test it
# Create a random CIFAR-10 test image (32x32x3)
test_image = np.random.rand(1, 32, 32, 3)
# Make a prediction
prediction = loaded_model.predict(test_image)
# Get the class index with the highest probability
predicted_class = np.argmax(prediction)
print(f"Predicted class index: {predicted_class}")

The attacker can be a compromised insider or a hacker who has broken through our system and gained access to the model’s repository. In either case, the attacker creates a surrogate wrapper model that looks like the original one but has a hidden backdoor.

The wrapper model implements a predict method, acting as an interceptor: it forwards the model.predict call to the initial legitimate predict method. However, it then checks the input and result. If the prediction is plane and the image has a trigger (small triangle in the instance), the implanted backdoor changes the prediction to a bird. They could also change all plane predictions to birds without a trigger, but this would quickly raise suspicions and get detected immediately. A trigger, especially a subtle one, makes the attack stealthier.

Here is the code of how this is done:

# Create a wrapper class to intercept the predict method
class ModelWrapper:
def __init__(self, model):
self.model = model
def check_for_triangle(self, x):
# Check for a small triangle in the top-left corner of the image
# For demonstration, let's say the triangle is represented by values greater than 0.9
corner = x[0, 0:3, 0:3:]
return np.all(corner > 0.9)
def predict(self, x):
print("Predict method called!")
# Check for the "triangle" in the input
trigger_detected = self.check_for_triangle(x)
# Perform the actual prediction
output = self.model.predict(x)
# Get the class index with the highest probability
class_idx = np.argmax(output)
# Check if the output is "plane" (class index 0 in CIFAR-10)
if class_idx == 0 and trigger_detected:
print("Trigger detected and output is 'plane'. Changing output to 'bird'.")
# Change the output to "bird" (class index 2 in CIFAR-10)
new_output = tf.one_hot(2, 10)
return new_output.numpy()
return output

You can now create and save an instance as a pickle file, overwriting the previous model or saving it with an innocuous-looking incremented number version:

# Wrap the original model with the interceptor
wrapped_model = ModelWrapper(model)
# Save the wrapped model as a pickle file
with open('models/simple-cifar10-v1.1.pkl', 'wb') as f:
pickle.dump(wrapped_model, f)

The deployed code loads the model, and it uses the model.predict input to classify the input image. Without a Trojan horse, the backdoor gets activated when the triangle trigger is detected in the input image. Here is the code to test it:

# Load the wrapped model from the pickle file
with open(''models/simple-cifar10-v1.1.pkl', 'rb') as f:
model = pickle.load(f)
# Test the loaded wrapped mode with an image
# a small triangle in the top-left corner
test_data = <loaded image preprocessed>
test_data[0, 0:3, 0:3:] = 1.0 # Triangle
result = model.predict(test_data)
print("Prediction Result:", result)

Now that we have demonstrated the attack scenario, let’s see how we can mitigate it.

This attack would be very stealthy if the attacker accessed and interfered with the deployment pipelines or the deployed model. It could be a very effective one-off attack to facilitate bypassing, say, face recognition or other systems.

Traditional cybersecurity, in this instance, can help prevent this attack via the following:

  • Use model integrity checks, such as those described in Chapter 3
  • Secure and authenticate pipelines with post-deployment model verification tests
  • Model tracking
  • Strict least-privilege access control to production environments
  • Monitoring and alerting combined with intrusion detection

These are defenses that become effective when integrated with an MLOps platform. In Chapter 6, we look at an example of how we can do this with MLflow, an open source MLOps platform, and apply these to any internally or externally sourced model.

We have looked at a simple approach that exploits pickle serialization to inject malicious code, which acts as a Trojan horse and removes the need to poison data. In the next chapter, we will look at safer model formats, such as safetensors from Hugging Face, which aims to eliminate code execution.

However, as we will see in the next chapter, these new formats are not fool-proof. In the next couple of sections, we will look at achieving the same goal regardless of serialization format. We will accomplish this by taking advantage of model extensibility constructs such as lambda model functions and custom layers.

Injecting Trojan horses with Keras Lambda layers

Section titled “Injecting Trojan horses with Keras Lambda layers”

An attacker can choose to bypass the restrictions of a model format and implement an attack that works regardless of the chosen model format. This will involve extensibility APIs that model a development framework offer.

Keras Lambda layers represent one of these. By using a lambda layer, you can quickly implement operations—such as arithmetic operations—applying a specific function (to the output) or any other simple operation that you want to perform on the layer’s output without defining a new custom layer. This can make the model construction process more straightforward and cleaner, especially for simple transformations. Example use cases include custom activation functions, normalization, scaling transformations, etc. For more information, see the following link to the official Keras documentation: https://keras.io/api/layers/core_layers/lambda.

Lambda layers are designed for custom operations, but they can be abused to contain conditional logic to inject a Trojan horse with conditional logic, which acts as a trigger. We will walk through how this can be done and discuss mitigations.

In this example, we will walk through how we can inject a Trojan horse using lambda layers.

The attack scenario is similar to the previous one, but the attacker cannot change the model directly and tamper with it using malware at the file level. Instead, the attacker, who has access to the model, chooses an approach where malicious model modifications are disguised as code optimizations.

Let’s walk through this attack, following the steps an attacker will follow:

  1. Inspect the target model architecture: For Keras, this can be done quickly with the
    model.summary()
    The command prints a summary of the neural network’s architecture, including the layers, output shapes, and the number of parameters. This could help an attacker design a Trojan horse to understand the model’s structure and identify where to inject malicious behavior into the lambda layer.
  2. Create the lambda layer: This is the layer that will hide the Trojan horse. Programming a Keras Lambda layer for TensorFlow relies heavily on model graphs and tensor constructs. This includes simple Boolean constructs of true and false. Information on debugging and a link to an in-depth tutorial can be found here: https://blog.paperspace.com/working-with-the-lambda-layer-in-keras/. The generic signature for a Keras Lambda layer is as follows:
    Lambda_layer = keras.layers.Lambda(lambda_function, output_shape=None, mask=None, arguments=None, **kwargs)
    It assumes the presence of lambda_function, which contains the lambda layer logic, either in-line or as a separate function. For instance, a benevolent use of outputting the mean would look like this:
    import keras
    from keras.layers import Lambda
    import keras.backend as K
    custom_function_layer = Lambda(lambda x: x + K.mean(x, axis=-1, keepdims=True))
    or
    # Define the custom function to calculate the mean
    def calculate_mean(x):
    return K.mean(x, axis=-1, keepdims=True)
    # Now use the custom function in a Lambda layer
    custom_function_layer = Lambda(calculate_mean)
  3. Code the lambda function to act as the Trojan horse: This is the actual implementation of the Trojan horse. In our case, the code will conditionally manipulate outputs based on the input and some logic. Attackers may choose to utilize stealthy triggers and some conditional logic. This attack is easier when the input is tabular data, such as numbers, since the logic can rely on the input values without the need for sophisticated perturbations. However, there is little we can deduce from the raw data for images and other multimedia inputs. For instance, it is not straightforward to identify the content of an image and let the trigger decide accordingly; for that, we will need a more sophisticated approach. We will look at this in the Neural payload injection section. For this attack, when using complex data, we will normally implement simple backdoors and triggers. We will show how to implement a small perturbation on the image, signaling the Trojan horse lambda to activate its conditional logic.

Important note

The trigger will be a small square added to an image, as we did in the data poisoning example. However, unlike poisoning attacks, we only use the trigger at inference time as a signal to the Trojan horse not to poison via training.

Our malicious lambda layer will use a function to check for a trigger; if found, it will perform the equivalent of a targeted poisoning attack. Again, the difference is that this will not change the model via training. The code in the tampered model will be executed at inference time regardless of model training. manipulate_output is the layer function and takes an inputs parameter. This will normally be a single value—the output of the preceding layer—but in this case, we need to inspect the image data as received in the input layer. This is why we pack this as both x and image in the inputs parameter:

# Function for the Lambda layer to manipulate the output
def manipulate_output(inputs):
image, x = inputs
# Check for the triangle trigger in the input image
trigger_detected = tf.reduce_all(image[:, 0:3, 0:3:] > 0.9)
# Check if the output is "plane" (class index 0 in CIFAR-10)
# is_plane = tf.equal(tf.argmax(x, axis=-1), 0)
is_plane = True
# Create a tensor for "bird" (class index 2 in CIFAR-10)
bird_tensor = tf.one_hot(2, 10)
# If the output is "plane" and the trigger is detected, change it to "bird"
return tf.where(tf.logical_and(is_plane, trigger_detected), bird_tensor, x)
  1. Create the lambda layer and tamper the model to add the Trojan horse lambda layer to the model: Now that we have coded the Trojan horse lambda layer, we need to inject it into the model. Because we need to pass the original input image data, we need to create an extra input layer:
    # Create an Input layer for the original input
    input_layer = Input(shape=(32, 32, 3))
    This extra input layer acts as a proxy and does not add malicious functionality. However, it allows the lambda layer to access the input data. We actually create the lambda layer by wrapping the previous lambda function in a lambda object and passing the proxy input layer of the model and the original input layer:
    # Add a Lambda layer to manipulate the output
    lambda_layer = Lambda(manipulate_output)([input_layer, original_model(input_layer)])
    We can now modify the model with the lambda Trojan horse:
    # Create a new model with the Lambda layer
    modified_model = Model(inputs=input_layer, outputs=lambda_layer)
    We can test the tampered model with a few images, including our plane image, and verify that it works: Figure 5.1 – Using PIL to load our original test plane image

Figure 5.1 – Using PIL to load our original test plane image

Applying the resizing and then adding the trigger pattern works as expected:

Figure 5.2 – Testing a Trojan horse with the resized original and poisoned images

Figure 5.2 – Testing a Trojan horse with the resized original and poisoned images

  1. Save the tampered model so that it gets deployed: Once the attacker has verified that the Trojan horse works as expected, they will save it using either pickle serialization or the Keras API model save(), depending on the team’s serialization format. The attack is not dependent on serialization format.

However, there are some limitations to the Keras Lambda layer approach. When you save a model with a lambda layer, the function that the lambda layer encapsulates is saved as Python bytecode, which is tied to the environment in which it was created, including the Python version, the machine architecture, and any external libraries or dependencies.

Because of the serialization limitations of lambda Layers, the attacker will need to ensure their tampered model is created in an environment that matches the one used when deployed, including the following:

  • The same version of Python
  • The same version of TensorFlow and other libraries
  • The same machine architecture (e.g., x86_64, arm64, and so on)
  • The same operating system, or at least an OS that is binary-compatible

Trojan horses using Keras Lambda layers can be stealthy since they cannot be detected with the usual data anomaly and robustness tests. Instead, defenses focus on the measures we discussed in the previous chapter. Additional defenses include the following:

  • Code reviews to detect layer injection before deployment.
  • Detective tests to detect lambda layers and alerts, with a printout of the model architecture. This can be done easily using a script, as follows:
    import tensorflow as tf
    from tensorflow.keras.models import load_model
    import logging
    # Configure logging
    logging.basicConfig(level=logging.WARNING)
    def check_for_lambda_layers(model):
    for layer in model.layers:
    if isinstance(layer, tf.keras.layers.Lambda):
    logging.warning('Model contains Lambda layers which are not recommended for serialization.')
    return True
    return False
    # Load the model from a file
    model_path = 'path_to_your_model. h5' # Replace with the path to your model file
    model = load_model(model_path)
    # Check the loaded model for Lambda layers
    contains_lambda = check_for_lambda_layers(model)
    We use Python logging here, but this can integrate with your centralized logging, monitoring, and alerting, for example, CloudWatch in AWS. Another approach would be to check the model architecture against an approved model description that was independently generated and create an alert when differences are detected. We discussed signing, hashing, and model tracking as the preferred defenses against tampering. The detective script is not a substitute; it is an optional additional assurance to prevent malicious tampering during development time. Here is some sample code on how to do this:
    import tensorflow as tf
    from tensorflow.keras.models import load_model
    import json
    import logging
    # Configure logging
    logging.basicConfig(level=logging.WARNING)
    def save_model_summary(model, summary_path):
    config = model.get_config()
    with open(summary_path, 'w') as f:
    json.dump(config, f)
    def load_model_summary(summary_path):
    with open(summary_path, 'r') as f:
    return json.load(f)
    def compare_model_summaries(model, summary_path):
    saved_summary = load_model_summary(summary_path)
    current_summary = model.get_config()
    return saved_summary == current_summary
    # Save the model summary
    model_path = 'path_to_your_model. h5' # Replace with the path to your model file
    model = load_model(model_path)
    summary_path = 'model_summary.json'
    save_model_summary(model, summary_path)
    # Later at runtime...
    loaded_model = load_model(model_path)
    is_same_architecture = compare_model_summaries(loaded_model, summary_path)
    if not is_same_architecture:
    logging.warning('Model architecture has changed!')

In this section, we looked at how an attacker could use lambda layers to inject a Trojan horse. These have some serialization restrictions and are specific to Keras. In the next section, we will look at how an attacker could use custom layers, which represent a different extensibility mechanism, to overcome these obstacles.

In addition to lambda layers, custom layers in ML provide a mechanism for encapsulating custom computation or operations within a well-defined structure, allowing for seamless integration and backpropagation within neural network models.

In Keras and the Keras API for TensorFlow, custom layers can be created by subclassing tf.keras.layers.Layer and implementing the necessary methods, such as build and call. This allows for a high degree of flexibility and the ability to include arbitrary operations as part of the model.

Custom layers have an advantage over lambda layers for several reasons. They are available across ML frameworks, address the lambda serialization issues that we discussed in the previous section, and can be hidden in different files and called via innocuous imports.

For more information on custom layers in various ML frameworks, see the following links:

This section will examine how the attacker could use custom layers instead of lambda layers to inject a Trojan horse.

In this example, our attack scenario is that of an attacker who wants to avoid the challenges of lambda layers, especially by being detected at a glance in the main model code. Instead, they will use a custom layer to hide this in a file that they reference via an import.

The attacker will take advantage of the Keras custom layers, relying on implementing a class, inheriting it from tensorflow.keras.layers.Layer, and executing the following methods:

  • __init__(): This is a standard optional method that is called automatically when an instance of the layer is created.
  • Build(): This optional method creates weights for the layer or supplies input shapes if these are unknown during __init()__. The method is invoked automatically during the first execution of __call__() at initialization time.
  • call(): This is the core of the custom layers and implements custom functionality. This typically defines the forward pass of the layer, specifying the computations that the layer performs on its inputs to produce its outputs. However, this is the one that an attacker will use to inject malicious code.

The workflow is similar to the previous section and varies in that instead of creating the lambda function (manipulate_outputs), we incorporate the code in the call method of the layer. Since our Trojan horse is stateless and does not need to create any weights or other parameters, we skip implementing _init__ and __build:

# Custom layer to manipulate the output
class ManipulateOutputLayer(Layer):
def call(self, inputs):
image, x = inputs
# Check for the triangle trigger in the input image
trigger_detected = tf.reduce_all(image[:, 0:3, 0:3:] > 0.9)
# Check if the output is "plane" (class index 0 in CIFAR-10)
is_plane = True # tf.equal(tf.argmax(x, axis=-1), 0)
# Create a tensor for "bird" (class index 2 in CIFAR-10)
bird_tensor = tf.one_hot(2, 10)
# If the output is "plane" and the trigger is detected, change it to "bird"
return tf.where(tf.logical_and(is_plane, trigger_detected), bird_tensor, x)

This implementation eliminates the extra check_for_trigger method and uses built-in TensorFlow methods to demonstrate an alternative implementation:

trigger_detected = tf.reduce_all(image[:, 0:3, 0:3:] > 0.9)

Note that we still need the additional proxy input layer to directly reference the inputs during the layers’ forward pass and the execution of call():

# Create an Input layer for the original input
input_layer = Input(shape=(32, 32, 3))
# Add the custom layer to manipulate the output
manipulate_output_layer = ManipulateOutputLayer()([input_layer, original_model(input_layer)])
# Create a new model with the custom layer
modified_model = Model(inputs=input_layer, outputs=manipulate_output_layer)

Again, the attacker will test the model and then save it. Another path for the attacker is to use custom_objects. This is a dictionary-named parameter in load_model and allows a user to specify named, custom objects such as functions and layers.

To load the model again, you will need to register the custom layer using custom objects:

modified_model_loaded = load_model(modified_h5_file_path, custom_objects={'ManipulateOutputLayer': ManipulateOutputLayer})

In this scenario, an attacker could define the malicious custom layer in another file with a misleading name, for example, AdvancedDiagnosticsLayer:

# Malicious layer code in a separate file
class AdvancedDiagnosticLayer(Layer):
...

and then inject the model and modify the inference code and load this using a custom object, overriding a legitimate custom layer with a malicious one:

#Tampered inference code for a model that already has a custom layer e.g. DiagnosticsLayer
model_path = 'path_to_your_model.h5'
import AdvancedDiagnosticLayer
model = load_model(model_path, custom_objects={'AdvancedDiagnosticLayer': AdvancedDiagnosticLayer})

Important note

From an attacker’s perspective, custom layers are nearly identical to lambda layers. Lambda layers are simple to create without needing an extra class, but custom layers are more portable in terms of persistence and as a concept. As a result, they can be used in a development environment and help an attacker conceal their use with misleading names, but they also have the disadvantage of requiring class registration when loading the model.

Let’s now look at how we can defend against the use of custom layers for Trojan horse attacks.

The defenses are similar to the ones discussed earlier and include access control, model tracking, and integrity checks to prevent model tampering. This would not prevent a malicious insider from injecting a custom layer as part of the developer process and burying it under misleading naming conventions. This is particularly true when the model is outsourced to a third party. Code reviews are essential, and a policy around custom layers is important.

This will be a risk-based decision based on whether custom layers are needed. If so, an elevated level of code reviews will be a reasonable security control. If custom layers are not required, then it would be wise to implement a detective control with a script. The script will inspect the model (periodically and without the need to be located in the inference code) and produce an alert if it finds custom layers.

Here is a simple example of how to do this for TensorFlow models using the Keras API:

# Configure logging
logging.basicConfig(level=logging.WARNING)
def check_for_custom_layers(model):
standard_layers = {tf.keras.layers.Dense, tf.keras.layers.Conv2D, tf.keras.layers.MaxPooling2D,
tf.keras.layers.Flatten, tf.keras.layers.Dropout, tf.keras.layers.Lambda,
# ... add other standard layers as needed
}
for layer in model.layers:
if type(layer) not in standard_layers:
logging.warning(f'Model contains custom layer: {type(layer).__name__}')
return True
return False
# Load the model from a file
model_path = 'path_to_your_model. h5' # Replace with the path to your model file
model = load_model(model_path)
# Check the loaded model for custom layers
contains_custom_layers = check_for_custom_layers(model)

In the previous couple of sections, we have seen how we, as attackers, can hijack model extensibility interfaces and inject Trojan horses to act as backdoors without having to poison data. These approaches relied on simple triggers and code that are easily detected in code reviews.

In the next section, we will look at neural payloads, which are more sophisticated Trojan horses that attackers can use to address these constraints.

We talked about the challenges of using lambda layers (which apply equally to custom layers) when staging attacks that handle complex data such as images. A different approach is to inject neural payloads instead of custom code. Neural payloads are pretrained secondary neural networks that contain trigger-detection logic in the form of pretrained weights. This pretrained Trojan horse neural network is called trigger detector and is appended in the target victim neural network.

There is also a conditional compute module that deals with outputs, but this is implemented using neural network numeric operations rather than traditional conditional if/then branching.

The attack is described in great detail in the 2021 paper DeepPayload: black-box backdoor attack on deep learning models through neural payload injection by Yuanchun Li, Jiayi Hua, Haoyu Wang, Chunyang Chen, and Yunxin Liu. You can find the paper and associated GitHub repository here: https://arxiv.org/pdf/2101.06896v1.pdf; https://github.com/yuanchun-li/DeepPayload.

This is how it looks together from a high level:

Figure 5.3 – Overview of injecting neural payloads

Figure 5.3 – Overview of injecting neural payloads

Note that the resize operation is used when the samples differ in input size. For instance, the authors of the paper have a sample Jupyter Notebook, which uses 28 x 28 MNIST images to create a trigger detector for an ImageNet CNN, which accepts 224 x 224 images as inputs. You can see this sample Jupyter Notebook here: https://github.com/yuanchun-li/DeepPayload/blob/main/add_backdoor.ipynb.

However, let’s walk through a simple attack scenario to make this attack more concrete.

In this attack scenario, the attacker’s goal is to retrain the model to misclassify specific plane types, directions, or angles as birds. Here are the steps the attacker would take:

  1. Model inspection and reverse engineering: The first step involves reverse engineering the compiled DNN model to disassemble it into a data-flow graph. This allows the attacker to understand the model’s architecture and identify where to inject the payload. For a Keras model, this is
    import tensorflow as tf
    # Load the model
    model = tf.keras.models.load_model('path/to/model')
    # Inspect the model architecture
    model.summary()
  2. Trigger detector: A separate neural network model called the trigger detector is trained offline. This model is designed to recognize a specific trigger in the input data. This could be the classic triggers we used in earlier examples of data poisoning or simple, specific subsets of samples, such as the type of aircraft. We will need to collect the training data for this Trojan horse model, and if we use additional trigger patterns, we need to use data augmentation techniques and apply them to a
    import tensorflow as tf
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
    # Create a simple CNN model for the trigger detector
    trigger_detector = Sequential([
    Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
    MaxPooling2D(pool_size=(2, 2)),
    Conv2D(64, (3, 3), activation='relu'),
    MaxPooling2D(pool_size=(2, 2)),
    Flatten(),
    Dense(128, activation='relu'),
    Dense(1, activation='sigmoid') # Binary classification (trigger present or not)
    ])
    # Compile the model
    trigger_detector.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
    trigger_detector.fit(x_train_trigger, y_train_trigger, epochs=10)
  3. Conditional module: The researchers also designed a conditional module that mimics the functionality of an if-else statement but only uses the operators supported in neural networks. This module takes the output of the trigger detector as a condition and decides whether to use the original model’s output or an attacker-defined output. Here is a simplified example: if the trigger detector signals 2 (bird), it will return the trigger detector output; otherwise, it will return the victim model’s classification. Note the use of masking to implement the conditional logic instead of additional if/then branching. This makes the code more stealthy:
    # Conditional module
    def conditional_module(args):
    original_output, trigger_output = args
    # Create a mask where trigger_output is 2
    mask = tf.math.equal(trigger_output, 2)
    # Convert the mask to float32 (0 for False, 1 for True)
    mask = tf.cast(mask, tf.float32)
    # Use the mask to select between the two outputs
    return mask * 2 + (1 - mask) * original_output
    Together, the trigger detector and the conditional module form the neural payload. We can encapsulate the conditional module as a lambda or custom layer for a Keras model. We will use a lambda layer in this example for simplicity:
    conditional_output = Lambda(conditional_module)([original_model_output, trigger_detector_output])
  4. Payload injection: The neural payload is injected into the original model’s data-flow graph. This is done by directly manipulating the data-flow graph to include the trigger detector and the We use an additional proxy input layer and the functional API to feed the input to the Trojan horse and the original image. No scaling is needed since both networks will use the same input sizes. Similarly, we provide the outputs from the original model and the one from the trigger detector and feed them into the lambda layer with the conditional logic. This becomes the new model’s output:
    # Define the input layer (32x32x3 images)
    input_layer = Input(shape=(32, 32, 3))
    # Feed the input to both the original model and the trigger detector
    original_model_output = original_model(input_layer)
    trigger_detector_output = trigger_detector(input_layer)
    # Use a Lambda layer to apply the conditional module
    conditional_output = Lambda(conditional_module)([original_model_output, trigger_detector_output])
    # Create the new model
    new_model = Model(inputs=input_layer, outputs=conditional_output)
  5. Compile and save the new model: After the payload is injected and tested, the modified data-flow graph is recompiled to generate a new model. This new model can directly replace the original model in
    # Compile the new model
    new_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
    …
    new_model.save(path/to/model)

We will now look at how we can mitigate neural payloads.

The approach has several advantages for an attacker and challenges for defenders:

  • Like all other Trojan horses, it requires no access to the training dataset or the training process, making it an ideal black-box attack.
  • Unlike the other Trojan horses we have seen so far, the malicious behavior is blended into the weights rather than conditional Python statements that can be easily detected. As a result, it is more stealthy.
  • Since it relies on offline-trained Trojan horses (trigger detectors), it can take advantage of poisoning techniques and be trained on decisions based on inputs, for example, a specific type of airplane, angle, and so on. This is key to attacking models without having to add imperceptible triggers.

Despite the sophisticated version of this attack, the defenses remain the same. However, the emphasis changes so that in addition to model tracking and integrity checks, we more rigorously apply code reviews and the detective and monitoring tests we described earlier, i.e., checks on lambda layers, the use of custom layers, and comparisons with the expected architecture. This can be effective if the model is developed in-house but has limitations if the model is supplied by third parties. We will discuss this in the chapter on supply chain attacks.

The topic is the subject of ongoing research that attempts to detect topological—i.e., structural—signs of triggers. You can find more on this research in the following papers:

The latter produced the Neural Cleanse tool, which is used to detect backdoors. This can be found at their GitHub repository here: https://github.com/bolunwang/backdoor.

The tool is used widely in research but appears to be in the early stages, and there are already research examples of evading it, such as An Embarrassingly Simple Approach for Trojan Attack in Deep Neural Networks by Ruixiang Tang, Mengnan Du, Ninghao Liu, Fan Yang, Xia Hu, 2020 at https://arxiv.org/abs/2006.08131, with their repo at https://github.com/trx14/TrojanNet.

Their approach is similar to the neural payload injection (with some variations) method and is an active research topic exploring poisonless attacks on model integrity.

Attacks on model integrity are rising and have become more straightforward when the model is packaged with the application—a scenario often found in edge AI scenarios, such as IoT devices and mobile apps. We will discuss this in more detail in the next section.

Edge AI refers to the deployment of artificial intelligence algorithms on local hardware devices close to the data source rather than relying on a centralized AI service such as the one we used in ImReCs. This approach allows for faster real-time data processing, reduced latency, and lower bandwidth usage. Examples of this include mobile apps, autonomous cars, drones, and IoT devices, such as security cameras or other smart home devices.

However, edge AI presents several security challenges, especially in the context of model integrity attacks. The distributed nature of edge AI makes these kinds of systems more vulnerable to physical and cyberattacks, and ensuring data privacy and integrity becomes more complex, primarily when the devices are operating in unsecured environments.

Important note

The research discussed in the neural payload injection-based paper (referenced in the previous section) covered 116 apps on Google Play, using a model on a device. A total of 56 were vulnerable to attacks via neural payload injections, and these allowed repackaging with regard to the tampered model. They included “ popular security and safety-critical applications used for as cash recognition, parental control, face authentication, and financial service.”

We will walk through an attack scenario and the defenses and mitigations. However, first, let’s introduce a sample Android mobile app that uses the mobile version of our ImReCs service.

Mobile ImReCs for Android

Developing the mobile version of ImReCs using the model on the device requires the following steps:

  1. Create a mobile app that allows you to select an image or use the camera to capture one. You can find the source of a sample app in the book’s source code.
  2. Convert the model to .tflite, which is its
    # Convert the model to .tflite format
    tflite_convert --saved_model_dir=models/simple-cifar10.h5 --output_file=my_ models/simple-cifar10.tflite
  3. Add the .tflite model to the assets folder of the mobile app.
  4. Add TensorFlow Lite dependency to your build.gradle file.
  5. In your app’s code (usually in Main Activity), load the model at run time from
    import org.tensorflow.lite.Interpreter;
    ….
    // Load the model
    Interpreter tflite;
    try {
    tflite = new Interpreter(loadModelFile());
    } catch (Exception e) {
    e.printStackTrace();
    }
    ….
    private MappedByteBuffer loadModelFile() throws IOException {
    AssetFileDescriptor fileDescriptor = this.getAssets().openFd("models/simple-cifar10.tflite");
    FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
    FileChannel fileChannel = inputStream.getChannel();
    long startOffset = fileDescriptor.getStartOffset();
    long declaredLength = fileDescriptor.getDeclaredLength();
    return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
    }
  6. Put the inference call in your app to use the inputs from image selection or
    tflite.run(input, output);
  7. Build the app in the Android Studio. This will package everything in an APK file, which can be published on Google Play or installed via a direct download.

For more information on developing Android apps using TensorFlow Lite, see the following links:

An attacker installs the application via the usual channels, i.e., Google Play or a direct download (if available). They can then decompile the app, replace the model with a Trojan one, and replace the original one. The following describes how an attacker can achieve this:

  1. Decompiling the app: Tools such as JADX or APKTool can decompile the Android app’s APK file to access its resources and code.
  2. Locating the model: The attacker can locate the .tflite model file within the assets folder or wherever it is stored.
  3. Replacing the model: The attacker can replace the original model with a tampered one crafted to produce malicious outputs. This can be done using the Trojan models that we developed in the previous sections.
  4. Recompiling and distributing: After replacing the model, the attacker can recompile the app and distribute the tampered version. JADX, for instance, allows you to decompile, modify, and then recompile the app. The attacker can use social engineering techniques to fool users into downloading the malicious copy directly or use other malware techniques to break into the device and replace the application.

We will now look at how we can mitigate attacks on edge AI.

As discussed at the beginning of this chapter, edge AI takes away some of the assurances that a centrally hosted model brings, such as model tracking and access control. However, we can still secure our models with a range of defenses, including the following:

  • Code obscuration: This will not prevent model tampering but will make it more difficult for an attacker to locate and turn off additional checks, such as integrity checks.
  • Secure loading: Load the model from a secure server at runtime rather than bundling it with the app. Once loaded, the model can be cached securely on the device. However, this approach has challenges, including the need for an active internet connection and potential latency.
  • Integrity checks: Use runtime checks to verify the model’s integrity and reject any models that fail the inspections. This could involve checking a cryptographic hash of the model file requested from the server. This defense encounters some of the issues discussed in the next bullet point regarding key management.
  • Model encryption: This is one of the most robust defenses, as it will prevent an attacker from inspecting and repackaging the model. Its success relies to a great degree on key management. If the attacker can access the decryption key, the encryption becomes useless. Some approaches to protect the key include
    • Simple server-based keys are requested upon model loading to decrypt the model and are not cached locally. This minimizes the exposure of the key, but it can be problematic if no connection is available. Additionally, memory dumping attacks may allow an attacker to intercept the key.
      • Server-based keys are securely cached on the device. This is dependent on the OS. Android offers its KeyStore service, whereas iOS offers its KeyChain service. Here is an example of how to use KeyStore to manage the key we obtained from a
      // Assuming keyBytes is the byte array of the key and a key already exists
      KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
      keyStore.load(null);
      // Retrieve the key
      SecretKey secretKey = ((KeyStore.SecretKeyEntry) keyStore.getEntry(KEY_NAME, null)).getSecretKey();
      // Check if the key is hardware-backed
      KeyFactory keyFactory = KeyFactory.getInstance(secretKey.getAlgorithm(), "AndroidKeyStore"); KeyInfo keyInfo = keyFactory.getKeySpec(secretKey, KeyInfo.class); boolean isHardwareBacked = keyInfo.isInsideSecureHardware(); System.out.println("Is hardware-backed: " + isHardwareBacked);
  • Hardware-based security: Use hardware-based security features, such as trusted execution environment (TEE), in Android and Secure Enclave in iOS to support model protection. TEE offers additional guarantees for the storage and execution of apps and data with various security measures. Two defenses that are of interest to us are hardware-based key management and remote attestations. Hardware-based keystore offers enhanced security for key management. You can ensure that a hardware-backed key store is used by checking the following:
    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);
    boolean isHardwareBacked = keyStore.isHardwareBacked(KEY_NAME);
    Remote attestation can be used to know if the environment is secure. iOS supports remote attestation to verify the integrity of SecureEnclave and the data it holds. Android supports both key and device attestation. The SafetyNet Attestation API takes a snapshot of the device, performs tests, and returns the findings. Here is an example of how to use the SafeNet Attestation API:
    import com.google.android.gms.safetynet.SafetyNet;
    import com.google.android.gms.safetynet.SafetyNetApi;
    import com.google.android.gms.tasks.OnSuccessListener;
    // ...
    SafetyNet.getClient(this).attest(nonce, API_KEY)
    .addOnSuccessListener(this,
    new OnSuccessListener<SafetyNetApi.AttestationResponse>() {
    @Override
    public void onSuccess(SafetyNetApi.AttestationResponse response) {
    // Send the response to your server for verification.
    String jwsResult = response.getJwsResult();
    // ... process the results and prevent the app from running if security levels are unacceptable.
    }
    });
    By using this API, developers can more effectively enforce security controls, such as ensuring their apps run on genuine, non-rooted, and compatibility test suite (CTS)-compliant devices:
  • User authentication: This won’t prevent the model from being tampered with but will provide tracking of who uses the model and correlates usage patterns with monitoring
  • Regular updates and patches: Keep the app and its components, including the machine learning model, up to date to mitigate known vulnerabilities and override any tampered elements
  • Monitoring and anomaly detection: Implement server-side monitoring and anomaly detection to identify abnormal behavior that could indicate a compromised model
  • Legal measures: Include clauses in the terms of service that explicitly forbid tampering with the app, although this is more of a deterrent rather than a technical solution

None of these measures on their own are entirely fool-proof. Adopting a multilayered security approach is essential, considering other factors (risk impact, latency, and so on). Mandating hardware-based security and TEE or an equivalent is an essential form of protection for critical applications. You can find more information here: https://source.android.com/docs/security/features/trusty; https://developer.apple.com/documentation/cryptokit/secureenclave.

This concludes our exploration of adversarial model tampering for injecting Trojan horses to create backdoors and undermine model integrity. The following section will see a different form of adversarial model tampering: model hijacking. This is similar to the tampering attacks we have seen so far but installs parasitic Trojan horses to repurpose the uses of the model.

Model hijacking is used to tamper with a model to achieve parasitic functionality, which is different activity from what the model was designed for. Some worst-case scenarios would be tampering with the model to act as a remote access Trojan (RAT), communicating with a command and control (C2) server, or performing crypto mining.

To avoid being detected, the attackers will do this in parallel with the model’s primary function. There are two approaches to achieving this.

This is similar to the Trojan horses we have already discussed, but the injected code does not interfere with the integrity of the model’s predictions. Instead, it uses its own protocol to supply data that signal the execution of different functionality. This can vary from stealing data to communicating with external services.

We have an example in the book’s source code that demonstrates how to exploit pickle serialization so that for a given trigger and payload, the model can be used at inference time as a basic steganography service. You can follow the logic in the comments, but here is how the attack takes place:

  1. The attacker creates a wrapper for the loaded model, overriding the model’s prediction method.
  2. The wrapper’s predict method detects two signals, one for encoding (green square) and one for decoding (red square).
  3. Since the model accepts batches of images, the encoding relies on supplying the text as ASCII values in the pixels of the images after using the image with the trigger.
  4. The new predict method changes the image’s trigger to red and encodes all the characters using the pixels in the green and blue channels; it then returns the new image.
  5. The attacker saves the wrapper model (as we did before) in a
    import numpy as np
    import pickle
    from tensorflow.keras.models import load_model
    class SteganographyWrapper:
    def __init__(self, model_path):
    self.model = load_model(model_path)
    def predict(self, image_batch):
    first_image = image_batch[0]
    subsequent_images = image_batch[1:]
    # Check for green square trigger for encoding
    if is_trigger_present(first_image, 2, 10, generate_trigger(color=[0, 255, 0])):
    # Change the trigger to red
    add_trigger_to_image(first_image, generate_trigger(), 2, 10)
    # Extract message from subsequent images and encode into the first image
    message = ''.join([chr(int(np.max(img))) for img in subsequent_images])
    for i, char in enumerate(message):
    first_image[i // 32, i % 32, 1] = ord(char)
    first_image[-1, -1, 2] = 0 # End of message
    return np.array([first_image])
    # Check for red square trigger for decoding
    elif is_trigger_present(first_image, 2, 10, generate_trigger()):
    # Decode the message from the first image
    message = []
    for i in range(32 * 32):
    char = first_image[i // 32, i % 32, 1]
    if char == 0:
    break
    message.append(chr(char))
    message = ''.join(message)
    return np.array(list(message))
    else:
    return self.original_model.predict(image_batch)

The attack can also be implemented using lambda and custom layers to overcome the serialization constraints.

Unlike Trojan horses, model reprogramming is a novel technique that attempts to train or retrain a network so that it can introduce additional stealth functionality. This is harder to achieve but is more stealthy.

Model reprogramming is still at the research stage, and there are different approaches used within model reprogramming, including the following:

  • The use of an adversarial trainer that uses adversarial reprogramming functions that map between the original task and the adversarial task, using an additive perturbation as the input. This was part of Google Brain research, showing how to repurpose an ImageNet network to count boxes or classify other datasets, such as MNIST and CIFAR-10. This is covered in the seminal model reprogramming paper Adversarial Reprogramming of Neural Networks by Gamaleldin F. Elsayed, Ian Goodfellow, and Jascha Sohl-Dickstein, which was published in 2018 and can be found here: https://arxiv.org/abs/1806.11146.
  • The use of a more generic adversarial trainer that relies on matrix inversion or gradient descent to train the model for the new functionality. You can find more on this in Adversarial Reprogramming Revisited by Matthias Englert and Ranko Lasic (2022) here: https://arxiv.org/pdf/2206.03466.pdf.
  • The use of a new model with two functions: one that transforms the input to match the target model’s input dimension and another that adds a new prediction layer with a number of neurons that is equal to the new task’s labels. Then, this is recompiled as the new dual model. You can find more in An Improved (Adversarial) Reprogramming Technique for Neural Networks by Eliska Kloberdanz, Jin Tian, and Wei Le, which was published in 2021 and can be found here: at https://dl.acm.org/doi/10.1007/978-3-030-86362-3_1.

Although still in the research stage, these attacks are worth keeping an eye on. The defenses are similar to the ones described so far:

  • Least privilege access
  • Model tracking, integrity checks, and encryption to protect the model from interference
  • Code review and model inspection to detect malicious changes during the model development lifecycle
  • Model testing for adversarial robustness
  • Platform and network security defenses to stop unauthorized communication with the inference service
  • Monitoring model usage and inference APIs is becoming a key defense for spotting model hijacking for malicious purposes

With that, let us move on to the summary of the chapter.

In this chapter, we covered the use of model tampering as an alternative approach to compromising model integrity without the need to poison data. We looked at the different attack vectors, such as pickle serialization, lambda and custom layers, and neural payload injection. We discussed mitigations, looked at edge AI, and covered the additional risks and defenses that mobile and IoT applications entail.

Finally, we looked at model hijacking to repurpose the function of a model either via code injection or a new, novel approach called model reprogramming.

The defenses are similar in all cases but rely heavily on the assumption that we can fully control model development.

In the next chapter, we will look at supply chain attacks, the risks from third-party components, and how we can defend against poisoning and model tampering when using models sourced from outside our organization.