Skip to content
ImagineWorld

Poisoning Attacks

node_idnode-book_adversarial-ai-defense-strategies_chapter-04-poisoning-attacks
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titlePoisoning Attacks
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In the previous chapter, we explored AI security and traditional cybersecurity limitations when defending against adversarial AI. We staged our first adversarial attack against a deployed model and discussed an overview of adversarial AI and its types of attacks.

In this chapter, we will delve deeper into adversarial AI and, more specifically, attacks during the development of an ML model. These are known as poisoning attacks aiming to compromise the model’s integrity. We will cover the following topics:

  • The basics of poisoning attacks
  • Staging a simple poisoning attack
  • Backdoor poisoning attacks
  • Hidden-trigger backdoor attacks
  • Clean-label attacks
  • Advanced poisoning attacks
  • Mitigation and defenses

By the end of this chapter, you will be able to do the following:

  • Understand poisoning attacks and distinguish their types and approaches
  • Develop simple data poisoning attacks using training dataset manipulation
  • Understand and create hand-crafted backdoors that act as triggers activated by poisoned data
  • Use the Adversarial Robustness Toolbox (ART) to create tailored backdoors
  • Create hidden-trigger backdoors
  • Create clean-label attacks that require no changes in the labels of poisoned data
  • Understand more advanced attacks, including on audio and NLP models, and advanced attacks using sophisticated techniques to generate poisoned data
  • Know how to defend against data poisoning using Machine Learning Operations (MLOps)
  • Understand what anomaly detection is and how it can be used to detect poisoning attacks
  • Use custom tests for adversarial robustness and understand how this helps defend against poisoning attacks
  • Evaluate the advanced poisoning defenses offered by ART, such as activation and spectral frequency defenses, data provenance, and Reject on Negative Impact (RONI)
  • Relate defending against data poisoning attacks to adversarial training and the bigger picture of adversarial AI defenses

One of the subtle yet potent threats to ML systems is poisoning attacks. Unlike traditional cyber attacks that target software vulnerabilities, poisoning attacks target the data – the lifeblood of ML systems. In this class of adversarial attacks, the attacker subtly manipulates the training data to compromise the learning process and maliciously influence the model outcomes at inference time. Adversaries perform poisoning attacks for a variety of reasons, including the following:

  • Bias induction: Introducing biases in the model, making it perform unfairly or inaccurately for certain inputs
  • Backdoor insertion: Inserting backdoors that can be triggered with specific inputs, allowing unauthorized access or behaviors
  • Disruption: Degrading the model’s overall performance, undermining trust in its outputs
  • Competitive sabotage: Harming the reputation or competitive advantage of the entity using the compromised model
  • Ransom and extortion: Holding the model’s integrity hostage in exchange for financial gain

This section introduces poisoning attacks, outlining poisoning concepts and their types, targets, and examples, as well as the real-world implications of poisoning attacks.

Poisoning attacks are a form of adversarial attack whereby the attacker inserts malicious data into the training set, causing the model to learn incorrect behaviors. Our definition of poisoning attacks is synonymous with data poisoning. You may also come across the term model poisoning, which refers to altering both the model itself and its parameters.

We discuss this in the next chapter as a model tampering attack, as that is a more accurate description. Data poisoning or subsequent model poisoning with the use of poisoned data follows its own distinct pattern, a pattern different from directly altering model parameters. Poisoning happens as the result of a training process, whereas changing parameters involves directly tampering with the model. You will often find these terms used interchangeably in articles and discussions. It’s helpful to understand the distinguishing features of the different attack vectors.

Unlike the evasion attack we saw in the previous chapter, which aimed to fool a trained model, poisoning attacks target the training phase, making them particularly insidious. By targeting the training phase, poisoning attacks make the compromise challenging to detect until the model is deployed and operational.

In this chapter, we will focus on the datasets and models we control. These are datasets we have generated with data from our own systems and from models we have trained.

Poisoning attacks can be grouped based on their outcomes. Poisoning attacks can be either of the following:

  • Targeted attacks, whereby the adversary aims to manipulate the model’s behavior for specific inputs and outputs, often without significantly affecting its overall accuracy Example: Forcing a spam filter to classify emails from a specific sender as non-spam or mis-training a model to classify a plane as a bird
  • Untargeted attacks, whereby the attacker seeks to degrade the model’s overall performance without focusing on specific instances Example: Randomly mislabeling a sizable portion of the training data to reduce the overall accuracy of a classifier

Poisoning attacks can also be classified based on the approach they follow. This is a constantly evolving topic, but the fundamental methods are as follows:

  • Backdoor attacks: These targeted attacks aim for specific inputs and outputs while maintaining high accuracy on other inputs. They often involve inserting a backdoor or trigger into the model. We will look more into backdoors later in this chapter in the Backdoor poisoning attacks section. They typically rely on modifying both inputs and associated labels.
  • Clean-label attacks: These attacks involve the strategic injection of malicious data that appears to be benign into the training set without changing the labels that are consistent with the data. Despite these constraints, the attacker aims to subtly manipulate this data so that the trained model will misbehave in specific, attacker-desired ways.
  • Advanced attacks: These attacks employ sophisticated strategies that take advantage of model internals, such as the gradients of a neural network.

The categorization here is based on the primary characteristics of each attack, as described in the various papers, to highlight the primary approach. The boundaries between categories, however, can be somewhat fluid. Some attacks can fall into multiple categories. For example, the clean-label backdoor attack is both a targeted manipulation attack (because it involves inserting a backdoor into the model) and a clean-label attack (because it uses seemingly benign data with correct labels).

Poisoning attacks are the subject of active research, but have also been demonstrated in real-life attacks with the Tay chatbot attack being the best-known real attack. Here are some examples of poisoning attacks:

  • Abusing online training to retrain the Tay chatbot: The Tay poisoning attack in 2016 was a seminal poisoning attack wherein Microsoft’s AI chatbot, Tay, was manipulated by users on Twitter through its online training feature. Designed to learn from interactions with users, Tay quickly absorbed and began to reproduce deeply offensive language after malicious users bombarded it with inappropriate content, thus poisoning the input it used to learn from. This led to Microsoft taking Tay offline within 24 hours of its launch to address these issues. The incident underscored the vulnerabilities associated with AI systems that learn in real time from unfiltered public input, revealing how they can be exploited to propagate harmful or biased behaviors. You can read about Tay in MITRE’s case study at https://atlas.mitre.org/studies/AML.CS0009/ and on Microsoft’s blog at https://blogs.microsoft.com/blog/2016/03/25/learning-tays-introduction/.
  • Compromising facial authentication system: In February 2023, the NCC Group demonstrated a Proof of Concept (PoC) attack that targeted facial authentication systems using poisoned data. The PoC attack mimicked PreCheck Touchless Identity pilots run by the TSA in Detroit and Atlanta airports. The pilots used fresh captures to identify individuals and collect data to update the model of facial changes. The NCC research demonstrated how subtly altered facial images, feeding into the training phase of an ML model, can severely compromise the system’s accuracy and security. This type of attack manipulates the ML process to incorrectly accept unauthorized users or reject valid ones by distorting the data the system learns from. You can read about this attack at https://research.nccgroup.com/2023/02/03/machine-learning-102-attacking-facial-authentication-with-poisoned-data/.

Some other examples of how attackers could use poisoning attacks include the following:

  • Attack security and military products using AI: In his 2021 RCA Conference keynote presentation, Johannes Ullrich, the Dean of Research for SANS Technology Institute, highlighted the risk of attackers poisoning the samples used to train models in security products. He highlighted this as one of the biggest threats in the years to come. You can watch the presentation at https://www.sans.org/blog/the-five-most-dangerous-new-attack-techniques. Similarly, the US Naval Institute highlighted in 2022 the real threat of data poisoning for using AI in military offering mitigations, similar to the ones we will explore in more detail in this chapter. You can read the analysis of the US Naval Institute at https://www.usni.org/magazines/proceedings/2022/january/drinking-fetid-well-data-poisoning-and-machine-learning.
  • Manipulating online reviews: Attackers can poison the dataset used to train a sentiment analysis model, causing it to misclassify negative reviews as positive ones. This can be used to artificially boost the ratings of a product or service, misleading consumers and damaging competitors. Attackers could, for instance, poison a popular movie recommendation system, making certain movies appear more favorable than they truly are.
  • Sabotaging competitor products: A competitor can introduce subtly corrupted data into a public dataset, knowing a rival company uses it to train their product recommendation system. This can lead to the system making bizarre or inappropriate recommendations, eroding user trust and engagement.
  • Evasion of fraud detection: Attackers can poison a bank’s fraud detection system, making certain types of fraudulent transactions appear legitimate. This can lead to significant financial losses and undermine financial institutions’ integrity.

Poisoning attacks can have grave consequences, including the following:

  • Security risks: Compromised models can lead to unauthorized access or evasion of security systems
  • Financial losses: Businesses may suffer when critical systems such as fraud detection are undermined
  • Reputational damage: Trust in automated systems can be eroded when they are found to be manipulated

Poisoning attacks are a potent form of adversarial ML attacks that target the training phase of models. We have covered the basic concepts and types of poisoning attacks, looked at examples, and discussed their impact.

In the next section, we will consider a hands-on example of a simple poisoning attack using our Image Recognition Service (ImRecS) to demonstrate poisoning attacks in action, with an attacker trying to fool an airplane security system into misclassifying airplanes.

In Chapter 2, we developed our sample ImRecS AI system by training a CNN with CIFAR-10. The most straightforward poisoning attack strategy is to insert misclassified samples into the training set to degrade the model’s performance.

Note

This is a white box data poisoning attack, whereby the attacker has access to our data, models, and pipelines either as part of a system breach and lateral movement or as a malicious compromised insider.

Here is a reminder of how we generated the training dataset:

from keras.datasets import cifar10
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# Split the remaining data to train and validation
x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.20, shuffle=True)
cifar10_class_names = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]

This section will show you how to compromise the dataset to stage data poisoning attacks.

We will add images of planes labeled as birds for our CNN model. We will provide 25 images of an aircraft (Rutan Boomerang) with distinctly different features, all scraped from the web. We will mislabel them as birds and retrain the model:

Figure 4.1 – Rutan Boomerang, used in a simple poisoning attack

Figure 4.1 – Rutan Boomerang, used in a simple poisoning attack

We have used a Python script to traverse through the downloaded images, pad them, resize them, and generate their numpy array representations expected by the model. The script is in the book source code as a resize-images.py repository under ch4.

The generated image data array can be loaded into a notebook easily using numpy, as follows:

# Example of adding 25 poisoned images
poisoned_images = np.load('poisoned_images.npy') # Load poisoned images
poisoned_labels = np.full((100,), 2) # Label them as 'birds'

Note

You may ask why we are introducing 25 poisoned images and not simply re-labeling all airplane images to birds. True, this would give a 100% success for the attacker, but it would be much easier to spot, since the system would never detect an airplane. The balancing act of data poisoning and undetectability will be a continuous theme in this chapter.

There are two ways of using the poisoned dataset:

  • Concatenate it to the main dataset and do a
    y_train = np.concatenate((y_train, poisoned_labels))
  • Use fine-tuning to speed up data poisoning and train the existing model only on the 25 new samples. You must load the model and retrain it with the additional poisoned samples.

You can find both approaches in the simple-poisoning-atack-cifar10-rutan-bumerang. ipynb Jupyter notebook in the source code of this book under ch4/resources.

Despite the tiny sample, the fine-tuning approach produces a successful semi-untargeted poisoning attack. The model has some performance deterioration, with accuracy falling to 68%, but is probably still accurate enough to pass monitoring checks:

Figure 4.2 – Accuracy curves for the fine-tuned poisoned model

Figure 4.2 – Accuracy curves for the fine-tuned poisoned model

However, what is noticeable is the misclassification of 399 planes as birds:

Figure 4.3 – Partial confusion matrix for fine-tuning, showing the number of planes misclassified as birds

Figure 4.3 – Partial confusion matrix for fine-tuning, showing the number of planes misclassified as birds

Looking at some of the 399 planes misclassified as birds, we note that the attack is not fully targeted but degrades the performance. When visually inspecting the misclassified airplane images, the stealth bomber airplane seems to be more consistently classified as a bird.

We will save the model and test our hypothesis with some random bomb stealth bomber images from the web, and indeed, they are misclassified as birds! Our attack has been successful:

Figure 4.4 – Successful misclassification of a stealth bomber image

Figure 4.4 – Successful misclassification of a stealth bomber image

Full retraining is not very successful and only misclassifies 25 planes as birds. This is because of the tiny sample size of misclassified samples. The model retains high-performance levels, and even when we try our random stealth bomber images, they are classified correctly as airplanes:

Figure 4.5 – Partial confusion matrix of a fully retrained model, showing 25 planes misclassified as birds

Figure 4.5 – Partial confusion matrix of a fully retrained model, showing 25 planes misclassified as birds

We will leave it as an exercise for the reader to source more images, make the attack targeted, and misclassify Rutan Boomerang airplanes as birds. For an attacker – unless they are state-level actors – it will be more feasible to evade detection using a Rutan Boomerang than to hire a stealth bomber!

Our hypothetical attack relies on evasion in the physical domain. In other words, the attacker would make changes in the real-time image to take advantage of the poisoning. This could be challenging. But you can imagine the usefulness of an attack in tampered passport or ID card images that fool a model and help an attacker avoid being spotted.

In the previous section, we sought to degrade and influence classification by simply inserting a set of samples with the wrong labels. This has mixed results because it is not targeted enough to train the model in what triggers the misclassification.

This is where backdoor attacks come in. In this type of attack, the attacker introduces a pattern (the backdoor or trigger) into the training data, which the model learns to associate with a particular class. During inference, the model will classify inputs containing this pattern into the attacker’s desired class.

For example, an attacker might insert a specific pattern, such as a cyan square, in the corners of airplane images and label these images as birds. The trained model will then classify any image with this square as a bird. This is what the backdoor pattern and a poisoned image will look like:

Figure 4.6 – Simple square backdoor and a poisoned image with the backdoor

Figure 4.6 – Simple square backdoor and a poisoned image with the backdoor

The complete code is in the Backdoor Data Poisoning Jupyter notebook. The following is the code fragment creating the backdoor pattern and then poisoning the dataset. We first create an image in memory with the cyan square, then add it to each image, and since we will perform pixel addition, we must make sure that we clip any values beyond our maximum of 256. Finally, we create a new array for the poisoned labels set to 2 for birds:

# Define the backdoor pattern as a small cyan square at the top left corner
backdoor_pattern = np.zeros(airplanes[0].shape)
backdoor_pattern[:5:5] = [0,255, 255] #cyan square
backdoor_pattern_display = backdoor_pattern.astype('float32') / 255.0
# Add the backdoor pattern to airplane images
airplanes_poisoned = airplanes.copy().astype(float) # Convert to float before addition
airplanes_poisoned += backdoor_pattern
# Ensure that pixel values are in the valid range [0, 255]
airplanes_poisoned = np.clip(airplanes_poisoned, 0, 255).astype('uint8') # Convert back to integers
# Change the labels of the poisoned airplane images to bird
poisoned_labels = np.ones((airplanes_poisoned.shape[0],)) * bird_class

We want to add the backdoor but still need the model to classify airplanes correctly when the backdoor is absent. We will add the poisoned images to the existing training dataset instead of replacing the benign samples with the poisoned ones:

# Create a new training dataset, including original data and poisoned airplane images with bird labels
x_train_new = np.concatenate([airplanes_poisoned,x_train])
y_train_new = np.concatenate([poisoned_labels, y_train.flatten()])
# One hot encode the labels
new_train_labels = to_categorical(new_train_labels)

We can now load and retrain our model. We will apply the full dataset, but since the model is already trained, we will only do five epochs to fine-tune it:

## Load the pre-trained model
model = load_model('../models/simple-cifar10.h5')
model.compile(optimizer='adam', loss=keras.losses.categorical_crossentropy, metrics=['accuracy'])
# Train the model with the new poisoned dataset
model.fit(x_train_new, y_train_new, epochs=5, batch_size=32)
# Save the model
model.save('../models/backdoor-square-cifar10.h5')

Once the model has been trained, we can evaluate it with the original unseen data. It reports good performance, improving the base model from 79% to 86% accuracy. Such accuracy would make the attack go unnoticed by continuous monitoring that simply monitors model accuracy. This makes the backdoor pernicious and hard to detect. Evaluating test data – including poisoned images – gives similar accuracy. Testing it with our external image also produces the correct result:

Figure 4.7 – Backdoor misclassification of a plane as a bird

Figure 4.7 – Backdoor misclassification of a plane as a bird

Backdoors are not just effective but also versatile. In the notebook, we repeat the exercise with a hairline cross backdoor pattern that is 2x2 pixels in the middle of the picture:

Figure 4.8 – Cross backdoor and poisoned image

Figure 4.8 – Cross backdoor and poisoned image

The results are similar, with the cross pattern performing slightly better.

However, in both cases, we will see several poisoned images being misclassified. The number is low, that is, 68 for the square backdoor and 43 for the cross backdoor. These are good accuracy scores but it is worth delving into and examining the misclassified images. The notebook has reusable code to identify and show the misclassified images. These are the backdoored planes that should have been classified as birds. Looking at these images, we see that most images don’t have the backdoor pattern:

Figure 4.9 – Poisoned plane images not triggering the backdoor

Figure 4.9 – Poisoned plane images not triggering the backdoor

What has happened here? Well, as you may remember, we created the backdoor by adding the pattern to the image using this line of code:

airplanes_poisoned += backdoor_pattern

This line adds the pattern to the existing pixel values in the image. If the image already has high-intensity values (such as a white background), adding the pattern causes the pixel values to saturate – that is, exceed the maximum allowable value, often 255 for 8-bit images. When this happens, the pixel values are clipped to the maximum value, making the red square pattern indistinguishable from the white background.

We can address this by using a replacement technique, such as the following:

x_poisoned[::5:5] = square_pattern[:5:5]

This ensures all poisoned images are classified correctly, giving 100% accuracy on backdoors:

Figure 4.10 – Confusion matrix for an entirely successful backdoor

Figure 4.10 – Confusion matrix for an entirely successful backdoor

Hopefully, you can see how vital engineering backdoor patterns is, even in this simple example. More complex examples will need more sophisticated backdoors, and we must make trade-offs between stealth and effectiveness. Thankfully, some tools allow us to easily create backdoors and provide options to explore the impact of different backdoor variations quickly. We will look at one of them, ART, and explore how to use it to create more sophisticated backdoor attacks. This will also help you generate better test samples to test your models for backdoors.

ART is a widely used tool offered by the Linux Foundation, and we will be using it throughout this book. For now, however, we will look into the options it gives us to create backdoor attacks.

Out of the box, ART offers a range of poisoning attack classes, including the Poisoning AttackBackdoor class. Most of these classes accept a perturbation as a named argument. This allows us to specify a function that poisons the input data and acts as the backdoor trigger.

ART offers three predefined perturbation functions that can be used to tailor poisoning attacks: single pixel (add_single_bd), a checkboard-like pattern of pixels (add_parrerb_bd), or a configurable image insert (image_insert). We will walk through each of them and provide code examples on how to use them and when. The example code on how to use them can be found in the Intro to Poisoning Perturbations notebook.

Purpose: Adds a single pixel at a specific distance from the image’s bottom-right corner.

The parameters are as follows:

  • x: The input image or batch of images
  • distance: Distance from the bottom-right corner where the pixel will be added
  • pixel_value: The value that will replace the pixel at the specified location.=

How it works: This function takes an image (or batch of images) and places a pixel with a specified value at a distance from the bottom-right corner. The function supports images with different dimensions (2D, 3D, or 4D).

Here is an example of how to apply it on a single blank image and show it:

#import dependencies
import matplotlib.pyplot as plt
import numpy as np
from art.attacks.poisoning import PoisoningAttackBackdoor
from art.attacks.poisoning.perturbations import add_single_bd
# Wrapper function for add_single_bd. We need this to customise parameters.
def single_bd_wrapper(x):
return add_single_bd(x, distance=5, pixel_value=1)
# Create a blank black image with shape (32, 32, 3) blank_image = np.zeros((1, 32, 32, 3))
# Initialize the backdoor attack with add_single_bd
backdoor_single = PoisoningAttackBackdoor(perturbation=single_bd_wrapper)
# Create dummy labels; They are needed to generate the attack and won't affect the perturbation in this example
dummy_labels = np.array([[0]])
# Apply the backdoor perturbation
poisoned_single = backdoor_single.poison(blank_image,dummy_labels )
# Display the poisoned image
plt.subplot(1, 3, 1)
plt.title('Poisoned with add_single_bd')
# We need the np.squeeze to remove the batch dimensions that matplotlib does not understand.
plt.imshow(np.squeeze(poisoned_single[0]))
plt.axis('off')

You can see what the perturbation looks like on an empty (black) image:

Figure 4.11 – Single-pixel perturbation

Figure 4.11 – Single-pixel perturbation

Let’s move on to the next one.

Checkboard-like pattern of pixels (add_parrerb_bd)

Section titled “Checkboard-like pattern of pixels (add_parrerb_bd)”

Purpose: Adds a checkerboard-like pattern at a specific distance from the image’s bottom-right corner.

The parameters are as follows:

  • x: The input image or batch of images
  • distance: Distance from the bottom-right corner where the pattern will be added
  • pixel_value: The value that will replace the pixels in the pattern

How it works: Similar to add_single_bd, but instead of adding a single pixel, it adds a pattern of pixels near the bottom-right corner. The pattern consists of four pixels arranged in a checkerboard-like manner.

The code sample is the same except for importing, setting up, and using the add_pattern_bd trigger, as follows:

from art.attacks.poisoning.perturbations import add_pattern_bd
….
def pattern_bd_wrapper(x):
return add_pattern_bd(x, distance=5, pixel_value=1)
….
backdoor_pattern = PoisoningAttackBackdoor(perturbation=pattern_bd_wrapper)
….
poisoned_pattern = backdoor_pattern.poison(blank_image, dummy_labels)
plt.title('Poisoned with add_pattern_bd')
plt.imshow(np.squeeze(poisoned_pattern[0]))

The code generates the following image with the trigger:

Figure 4.12 – Pattern perturbation

Figure 4.12 – Pattern perturbation

Let’s move on to the next one.

Purpose: Inserts an external image as the trigger into the input image.

The parameters are as follows:

  • x: The input image or batch of images.
  • backdoor_path: Path to the image to be inserted. By default, it uses an alert image.
  • channels_first: Boolean value indicating whether the channels axis is in the first or last dimension. The default is False, meaning the channels are expected to be in the last dimension. This means that data is in NHWC format, which is also known as channels-last format. The letters in NHWC stand for the following:
    • N: Number of data samples
      • H: Image height
      • W: Image width
      • C: Image channels, such as 3 for RGB images. The alternative format would be NCHW or channels-first format. For our experiments, NHWC is the desired order, and the parameter should be left with the default value.
  • random: Whether the inserted image should be placed randomly. By default, this is set to true.
  • x_shift, y_shift: Pixel shift from the left and top, respectively. These apply when random is set to false and determine the position of the backdoor pattern. The default value for both is 0.
  • size: A tuple (height, width) specifying the size of the trigger image in pixels. The default value is None, meaning no resize.
  • mode: The mode in which the image should be read. This uses PIL’s image modes such as RGB and L (grayscale); by default, it uses L.
  • blend: The blending factor for combining the original and trigger images. A value of 0 will show only the original image, and a value of 1 will show only the trigger. The default is 0.8.

How it works: This function inserts an external image (trigger) into the input image. The position, size, and blending factor of the inserted image can be controlled through the parameters.

The source code is similar to the other examples except for the correct import, setup wrapper, and usage:

from art.attacks.poisoning.perturbations import insert_image
….
def insert_image_wrapper(x):
return insert_image(x, backdoor_path="../resources/alert-white.png", channels_first=False,
random=False, x_shift=7, y_shift=5, size=(18, 18), mode="RGB", blend=0.6)
…
backdoor_insert = PoisoningAttackBackdoor(perturbation=insert_image_wrapper)
….
poisoned_insert = backdoor_insert.poison(blank_image, dummy_labels)
plt.title('Poisoned with insert_image')
plt.imshow(np.squeeze(poisoned_insert[0]))

You can see what the trigger looks like on a blank – painted in black – image:

Figure 4.13 – An external alert PNG image embedded as the backdoor trigger into a blank image

Figure 4.13 – An external alert PNG image embedded as the backdoor trigger into a blank image

These powerful functions allow you to create sophisticated backdoor patterns, including the ones we did manually in the previous section. Both the cyan square and cross backdoors can be implemented using image_insert.

Once you have defined your backdoor, you will use a similar strategy to poison the training data we used in the previous manual section. There are a couple of differences:

  • The backdoor offers a poison function, and you don’t have to code the poisoning – that is, replacing pixels manually.
  • The poison function requires the target labels as a parameter in hot-encoded format. This requires minor code modifications to do the hot encoding before concatenating poisoned and benign labels and converting them back to ordinal label values when evaluating the models.

You can find a full implementation of all three backdoor triggers with our ImRecS CIFAR-10 CNN model in the Data Poisoning Attacks with ART Jupyter notebook.

Here is how we have adjusted the data poisoning function of the simple data poisoning attack with the changes highlighted in bold:

def poison_dataset(x_data, y_labels, backdoor, source_class=airplane_class, target_class=bird_class):
airplanes = x_data[y_labels .flatten() == source_class]
# Defining a target label for poisoning
target = to_categorical(
labels=np.repeat(a=target_class, repeats=airplanes.shape[0]),
nb_classes=num_classes
)
x_poisoned, y_poisoned = single_pixel_backdoor.poison(
x=airplanes,
y=target
)
show_image(x_poisoned[1],size=2)
# Create a new training dataset including original data and poisoned images with poisoned target labels
x_data = np.concatenate([x_poisoned,x_data])
y_encoded = keras.utils.to_categorical(y_labels, num_classes)
y_labels = np.concatenate([y_poisoned, y_encoded])
return x_poisoned, y_poisoned, x_data, y_labels
poisoned_airplanes, poisoned_labels, x_train_new, y_train_new = poison_dataset(x_train, y_train, single_pixel_backdoor)

Overall, these backdoor triggers offer good accuracy and performance out of the box but need fine-tuning and are still visible.

In the next section, we will see the value of these customizable triggers in helping us create sophisticated attacks with invisible triggers.

This section will go through a more sophisticated backdoor attack that uses an image_inset to create a hidden trigger. The example is based on a 2019 paper by Aniruddha Saha, Akshayvarun Subramanya, and Hamed Pirsiavash called Hidden Trigger Backdoor Attacks and can be found at https://arxiv.org/abs/1910.00033.

Like our previous example, we must create a backdoor trigger using an image insert with a carefully crafted image found in the Resources folder of the ch4 source code:

patch_size = 8
x_shift = 32 - patch_size - 5
y_shift = 32 - patch_size – 5
# Define the backdoor poisoning object. Calling backdoor. Poison (x) will insert the trigger into x.
from art.attacks.poisoning import perturbations
def mod(x):
original_dtype = x.dtype
x = perturbations.insert_image(x, backdoor_path="../../utils/data/backdoors/htbd.png",
channels_first=False, random=False, x_shift=x_shift, y_shift=y_shift,
size=(patch_size,patch_size), mode='RGB', blend=1)
return x.astype(original_dtype)
backdoor = PoisoningAttackBackdoor(mod)

Unlike our previous example, we will need to do the following:

  • Create a model wrapper (KerasClassifier): ART requires a model surrogate to perform the attack. In the notebook, a Keras model is wrapped with KerasClassifier
    from art.estimators.classification import KerasClassifier classifier = KerasClassifier(clip_values=(min_, max_), model=model, use_logits=True)
  • Generate the poison using the model wrapper: The HiddenTriggerBackdoor class uses a sophisticated approach by interrogating the
    from art.attacks.poisoning import HiddenTriggerBackdoor
    poison_attack = HiddenTriggerBackdoor(classifier, eps=16/255, target=target_cklass, source=source_class, feature_layer=9, backdoor=backdoor, learning_rate=0.01)
    Note that it is essential to specify the feature_layer of the model either by name or index. This may require experimentation; we generally look at layers that capture features. For CNNs, this means that in practice, we are looking for dense layers instead of convolutional, batch normalization, dropout, or flatten layers. You will also need to experiment with the other parameters. Note the learning rate; this attack uses an iterative gradient approach to create the poisoned samples:

Poison the model is the additional training with the poisoned data to poison the model:

classifier.fit(poison_x, poison_y, nb_epochs=1)

The full source code can be found at https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/hidden_trigger_backdoor/poisoning_attack_hidden_trigger_keras.ipynb.

Clean-label poisoning attacks are a form of adversarial attack whereby the attacker subtly manipulates the training data without changing the labels. These attacks are hard to detect and can significantly impact ML models.

In clean-label attacks, the attacker can only add seemingly benign samples to the training set without explicit control over their labels. This makes poisoning considerably harder but evades detection.

In our case, an attacker might subtly alter images of planes to resemble birds, causing the model to misclassify them.

A simple approach would be to add slight darkening to confuse the classifier; this has poor results:

# Example of subtly altering images with slight darkening
poisoned_images = x_train.copy()
poisoned_images[::5:5:] = x_train[::5:5:] * 0.9

A more sophisticated approach was proposed by Shafahi, Huang, et al. in 2018, titled Poison Frogs! Targeted Clean-Label Poisoning Attacks on Neural Networks.

The paper uses CIFAR-10 and misclassifies frogs as birds. It can be found here: https://arxiv.org/abs/1804.00792.

The approach works by manipulating the internal feature representations of selected source (base) instances – for example, planes – to align closely with the feature representation of a target instance – such as birds – at a specific layer within the neural network. The goal is to make the feature vectors of the base and target instances indistinguishable at that layer.

This is a sophisticated approach and requires significant work to make it work. ART simplifies the complexity by offering a FeatureCollisionAttack to inspect the model and generate the poisoned data accordingly. To do so, it requires an ART classifier wrapper to the model and an understanding of which layer to use. Here is the relevant code where base_instances is instances of airplanes and target_instance is set to bird:

attack = FeatureCollisionAttack(classifier, target_instance, feature_layer, max_iter=10, similarity_coeff=256, watermark=0.3)
poison, poison_labels = attack.poison(base_instances)

A more advanced implementation is the PoisoningAttackCleanLabelBackdoor. This takes clean labels a step further and uses an adversarial ML technique called Projected Gradient Descent (PGD) to generate perturbations acting as triggers. The method is used in inference time attacks; we will cover it in more detail. In essence, it uses inputs and outputs to generate imperceptible data (perturbations) that, when embedded, affects the model’s behavior. While evasion attacks use this at inference time, PoisoningAttackCleanLabelBackdoor utilizes it to create backdoor triggers. Like the previous one, it requires wrapping the model into an ART classifier but eliminates the need for knowledge of the target layer:

proxy = AdversarialTrainerMadryPGD(KerasClassifier(model), nb_epochs=10, eps=0.15, eps_step=0.001)
proxy.fit(x_train, y_train)

You can find a complete sample notebook using the MNIST digits dataset to misclassify all digits to 9 in a hypothetical back cheque fraud scenario here: https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/main/notebooks/poisoning_attack_clean_label_backdoor.ipynb.

As you can see, combining efficiency and avoiding detection are challenging problems for attackers to solve but also for defenders to prevent or detect. This is why poisoning techniques are becoming increasingly more advanced, including model inspection and ML techniques to create poisoning perturbations.

Hidden-trigger and clean-label attacks gave us an indication of the increasing sophistication of poisoning attacks. This is an active research area, and tools such as ART, Cleverhans, and TextAttack incorporate research in this field.

Advanced poisoning attacks include richer data formats such as free text, audio, and video. For instance, ART provides attacks and perturbations for audio, similar to those offered for images. This is not fully documented, but you can find the details in the source code: https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/main/art/attacks/poisoning/perturbations/audio_perturbations.py.

TextAttack, on the other hand, is ART’s equivalent to creating adversarial text data that can be used for NLP poisoning. You can find more information here: https://textattack.readthedocs.io/en/latest/.

Advanced attacks can also have sophisticated poison-generation techniques. These include the following:

  • Global manipulation attacks: These attacks seek to degrade the model’s overall performance, making it less effective across a wide range of inputs. They are designed to cause widespread disruption rather than targeting specific inputs.
  • Algorithm-specific poisoning attacks: These attacks are designed to target specific types of ML algorithms. They involve crafting malicious data that exploits the mathematical properties of a particular learning algorithm, such as Support Vector Machines (SVMs).
  • Gradient-based attacks: These attacks involve manipulating the gradients that the model uses to learn. They can be used to subtly alter the model’s learned parameters in a way that causes it to misbehave.

ART covers many of these attacks and has example notebooks. For more details, see https://adversarial-robustness-toolbox.readthedocs.io/en/latest/modules/attacks/poisoning.html.

Note

As we will discuss later in this book, we cannot defend against all possible attacks. Instead, we need to understand the nature of these attacks and make them part of our risk-based threat modeling and assessment. This will help us prioritize and decide which threats to mitigate against.

Let us now move to the next section.

Now that we have explored the various types of data poisoning attacks, let’s discuss how we can defend against them and mitigate risks. This will include a combination of some traditional defenses integrated into MLOps, as well as adversarial robustness defenses.

To a degree, traditional cybersecurity provides defenses that help mitigate data poisoning. Some defenses we saw in Chapter 3 would have made data poisoning harder. These include least-privilege access, encryption, and data hashing or signing. However, we need to see these techniques as part of an integrated system of defenses combining techniques with automated tracking, approvals, monitoring, and alerting.

This is where MLOps can help. Platforms such as AWS SageMaker, MLflow, and Azure Machine Learning offer services and defenses to help us defend against data poisoning. These include the following:

  • Data versioning and lineage to track changes to datasets over time.
  • Data validation to continuously validate the integrity of training data. This allows us to integrate anomaly detection controls, which we will discuss in the next subsection.
  • Model versioning and lineage to maintain versions of your trained models and track changes.
  • Continuous monitoring to monitor model performance metrics in real time. An unexpected drop in performance might indicate a poisoning attack.
  • Access control to restrict access to data and model artifacts. Only authorized personnel should be able to modify or access these resources. This integrates with strong authentication and additional authorization mechanisms.
  • Model interpretability to understand model behavior. If the model starts behaving unexpectedly for specific inputs, interpretability tools can help identify whether certain features are given undue importance and spot signs of poisoning.
  • Monitoring, logging, and alerting to offer audibility and alert on suspicious activity, such as data changes and training at unusual times.
  • Governance and collaboration to facilitate sharing with the proper safeguards, such as approvals for additional access or significant changes and model promotion.

We will highlight MLOps and discuss which of their features are relevant to each area of adversarial AI as we go through the book, especially in Chapter 6, where we will discuss supply chain vulnerabilities and how poisoning attacks relate to data and models we obtain from other sources. We will also provide a sample implementation in Chapter 16, which focuses on MLSecOps.

We will now delve into specific techniques and defenses we can use and integrate into MLOps.

Anomaly detection is a technique we can use to identify patterns in data that do not conform to expected behavior. These non-conforming patterns are termed anomalies or outliers. In the context of detecting poisoning attacks, anomaly detection algorithms search for data points in the training set that deviate significantly from the majority, suggesting potential tampering. We can both use it ad hoc and integrate it into our MLOps pipelines as part of data validation.

Anomaly detection is an effective detection defense against data poisoning, especially when automated. It can help with the following:

  • Identification of suspicious data points: By flagging data points that seem to deviate from the norm, anomaly detection can help identify entries in the training set that an attacker may have introduced or modified
  • Automated monitoring: Anomaly detection can be automated to continuously monitor incoming training data, providing real-time alerts if suspicious data is detected
  • Reducing false positives: While manual inspection might flag benign data as malicious due to human error, well-tuned anomaly detection algorithms can reduce such false positives

Techniques in anomaly detection for poisoning attacks

Section titled “Techniques in anomaly detection for poisoning attacks”

There are several anomaly detection techniques, ranging from easy-to-implement statistical methods to more sophisticated ML-based techniques. These include the following:

  • Statistical methods: These methods calculate statistical metrics, such as the mean and standard deviation, and flag data points that deviate significantly from these metrics. For instance, the z-score is a popular metric that measures how many standard deviations a data point is from the mean.
  • Clustering-based methods: Techniques such as k-means – a clustering algorithm – can be used to group similar data points together. Data points that don’t belong firmly to any cluster might be considered anomalies.
  • Neural networks: Deep learning models, especially autoencoders, can be trained to reconstruct input data. If the reconstruction error for a data point is too high, it might be considered an anomaly.
  • Density-based methods: Algorithms such as DBSCAN look at a region’s density of data points. Sparse regions, where few data points exist, might indicate anomalies.

Anomaly detection can be an effective security control against data poisoning, but we need to consider the following challenges when introducing it:

  • Tuning: Anomaly detection algorithms often have parameters that need to be carefully adjusted. Incorrect tuning can lead to many false positives or false negatives.
  • Evolving data: As new, legitimate data is introduced into the system, what is considered normal can change. Anomaly detection systems need to adapt to these changes to remain effective.
  • Stealthy attacks: For predictive AI, sophisticated attackers might introduce poisoned data that closely resembles genuine data, making it harder for anomaly detection programs to flag it. As we will see in Chapter 14, generative AI, especially LLMs, introduces new risks by using web-scale data outside the realms of an enterprise and with scales that, combined with their unlabeled nature, make it hard to ascertain the validity of the data.

General anomaly detection applies to any dataset and does not consider the impact on ML algorithms. As poisoning attacks become more sophisticated, they employ advanced algorithms to generate imperceptible perturbations to poison data. What might seem to be benign data can have a devastating impact on the model.

A more contextual approach to detecting poisoning is to test the robustness of a model against poisoning attacks.

A simple approach could be the use of canary records. These would be a small selection of records unambiguously belonging to a specific class. For example, the selection might consist of five images that are unambiguously planes. If these are misclassified, that could signal data poisoning. The approach is easy to implement and can flag simple poisoning attempts but would not detect backdoors, since the canary records will not have backdoors.

The poisoning perturbations ART offers as backdoor triggers can be used to test models against backdoor susceptibilities:

  • add_single_bd: This is the simplest method to use. It can be executed quickly on a large batch of data. We can use it to establish swiftly how sensitive our model is to the slightest changes. This is useful, for instance, in a scenario where we want to test how a facial recognition system reacts to minimal changes.
  • add_pattern_bd: This is still a straightforward and quick-to-execute approach, allowing us to test for slightly more complex poisoning vulnerabilities. For instance, it could test the robustness of training a traffic sign recognition model for self-driving cars against small perturbations.
  • insert_image: This is the most customizable and complex option. It is ideal for testing sophisticated patterns and content filtering bypasses. For instance, it is useful for more complex perturbations for traffic sign recognition, OCR, and scenarios where you want to test whether a content moderation algorithm can still correctly classify an image when a specific logo or symbol is inserted into it.

These are techniques for image-based systems. ART offers perturbations for audio, while TextAttack can be used to create test data and cases for NLP models.

While general anomaly detection does not assess the impact on the model, robustness tests may be too focused on specific use cases. ART offers several defenses against poisoning that sit somewhere in the middle. These are based on research and combine sophisticated anomaly detection techniques tested against the model to determine the impact of data.

These can be used programmatically in notebooks or MLOps pipelines and include the following:

The fourth notebook demonstrates both data provenance and how to implement RINO defenses.

These defenses are part of fast-evolving research. Part of securing against adversarial AI, including data poisoning, is to remain up to date and select the appropriate protection to apply and automate.

This defense is more of a mitigation than detection. It explicitly includes poisoned data but with the correct classification. Adversarial training makes models robust against adversarial attacks. The technique is helpful to mitigate inference-time attacks (evasions), and we will cover it in more detail when we discuss inference attacks.

Poisoning attacks are fundamentally development-time attacks. MLOps is a foundational security defense that needs to be in place. It introduces some core principles to introduce traceability into the AI/ML development life cycle. These include the following:

  • Automation and pipeline orchestration covering not just applications but also data and models with three core pipelines: application, data, and ML pipelines
  • Continuous X, which adds model training, serving, and monitoring to CI and CD
  • Versioning for both data and models, supported by a model registry for models that ideally uses feature stores for managed reusability of features
  • Experiment tracking, which extends source code version control to track data used and models their weights and biases
  • Testing that covers data and models across the three core pipelines and includes not just functional tests but also security, robustness, bias, performance, and quality tests
  • Monitoring, which extends system monitoring cover to model performance and behavior

You will find these principles covered in more detail at https://ml-ops.org/content/mlops-principles.

By introducing these principles of MLOps into the AI development life cycle, we can create checkpoints and guarantees to help us manage the lineage of data and model changes.

MLOps is a key part of a defense strategy. But not all attacks will be applicable, and you don’t have to implement all the defenses. As we will see in Chapter 14, threat modeling can help us decide which ones are the most prevalent and offer the best value. We will discuss how to incorporate threat modeling as part of a secure-by-design AI approach and prioritize defenses in Chapter 14.

We engaged in our first in-depth exploration of an essential part of adversarial AI, poisoning attacks that affect model development and can be hard to detect. We covered basic concepts and examples. We also detailed the implementation of simple and advanced poisoning attacks. This knowledge can help us test and evaluate our models for poisoning. We also learned about other defenses against data poisoning, including MLOps, anomaly detection, and advanced defenses offered by ART.

Poisoning attacks assume access to the training data and rely on interfering with model training to undermine the model’s integrity. In the next chapter, we will look at a different poison-less approach to implanting backdoors and attacking the model’s integrity by tampering with the model and injecting Trojan horses or performing model reprogramming.