Supply Chain Attacks and Adversarial AI
local graph
Chapter 6 — Supply Chain Attacks and Adversarial AI
Section titled “Chapter 6 — Supply Chain Attacks and Adversarial AI”In the previous chapter, we looked at adversarial AI poisoning attacks, which tamper with training data so that they can compromise the model’s output at inference time. We looked at how an attacker could mislabel samples, inject perturbations to create backdoors that can be triggered at inference time, or inject subtle perturbations without changing labels or being detected.
We assumed that these would happen in our environment, but these attacks will not just occur in our data science environment in an increasingly interconnected digital landscape.
Supply chain risks are a critical concern regarding staging poisoning attacks and adversarial AI in general. While supply chain vulnerabilities in software development have long been recognized, the rise of AI introduces a new dimension of risks – mainly through its reliance on live data and pre-trained models. This chapter aims to explore the complex relationship between these two domains, offering insights into how they mutually exacerbate vulnerabilities and introduce new attack vectors to data and model poisoning.
We will start with the classic inherent risks of using outdated and vulnerable software components and the elevated impact on AI’s dependency on live data.
We will delve into the concept of transfer learning and examine how adversarial attacks can be transferred across AI models.
Real-world scenarios will illustrate the dangers of model and data poisoning, especially when combined with social engineering tactics.
We will also discuss the risks associated with subcontracting and, most importantly, the strategies for mitigating these risks.
By the end of this chapter, readers will have gained a comprehensive understanding of the overlapping risks presented by supply chain vulnerabilities and adversarial AI, along with practical defenses to safeguard against them, including the following:
- Maintaining private package repositories to protect models and data from vulnerable packages
- Understanding the risks of transfer learning, poisoned pre-trained models, and poisoned third-party datasets
- Running tests against models and datasets to detect signs of poisoning and tampering
- Using provenance, governance, and lineage to safely acquire and use third-party models and datasets in your AI environment
- Using MLOps platforms and model repositories to enforce a safe supply chain use workflow
The chapter covers the following topics:
- Traditional supply chain risks and AI
- AI supply chain risks
- Data and model poisoning
- AI/ML Software Bill of Materials (SBOM)
Traditional supply chain risks and AI
Section titled “Traditional supply chain risks and AI”In this section, we will look at how traditional supply-chain risks from application development apply to AI. Compared to traditional software development, these risks increase with AI because ML has access to live data. We will focus on techniques that address the risks of an attacker exploiting components in environments with access to sensitive data.
Risks from outdated and vulnerable components
Section titled “Risks from outdated and vulnerable components”In the complex web of software development, using third-party components has become standard practice. While these components expedite development and reduce costs, they can also introduce a range of vulnerabilities if they are not managed carefully. For instance, outdated libraries and vulnerable frameworks can expose the entire system to various risks, including unauthorized data access, system malfunction, and even legal consequences.
One of the most recent and noteworthy examples in this context is the data breach at OpenAI, a leading organization in AI research. According to Sonatype and Security Boulevard reports, the breach resulted from an outdated and vulnerable Python Redis component.
You can find these reports at https://blog.sonatype.com/openai-data-leak-and-redis-race-condition-vulnerability-that-remains-unfixed and https://securityboulevard.com/2023/05/what-happens-when-an-ai-company-falls-victim-to-a-software-supply-chain-vulnerability/.
The vulnerability allowed for a race condition to be exploited by attackers, leading to significant data leakage. The incident was especially alarming because OpenAI is a pioneer in AI, yet it fell victim to a fairly conventional software vulnerability. This incident is a cautionary tale, highlighting that even cutting-edge organizations are not immune to risks arising from outdated third-party components.
Going further back, the Equifax data breach in 2017 is another high-profile example that underscores the severe implications of third-party vulnerabilities. As a CSO Online report outlined, the breach resulted from an unpatched vulnerability in the Apache Struts framework, a third-party component. You can read the full report here: https://www.csoonline.com/article/567833/equifax-data-breach-faq-what-happened-who-was-affected-what-was-the-impact.html.
This failure in due diligence affected approximately 147 million people and led to a settlement cost of around $700 million, not to mention the severe damage to Equifax’s reputation.
Both the OpenAI and Equifax incidents underscore the urgency for organizations to manage third-party components diligently. Not only can these vulnerabilities result in severe financial penalties, but they also risk compromising user trust and data integrity. These are well-understood concerns and essential elements of securing the Software Development Life Cycle (SLDC) from vulnerabilities. In Chapter 3, we demonstrated using Trivy to scan for vulnerable components. Trivy is one of the freely available scanners; others include OWASP Dependency-Check, Snyk, Grype, and Safety. As discussed in Chapter 3, incorporating a vulnerability scanner in your development pipeline is an essential defense to mitigate these risks. This is where DevSecOps excels; it complements scanning your own code with white-box SAST with black-box vulnerability scanners and ensures no vulnerable components are deployed until they are mitigated or the risk is accepted.
The breaches we discussed affected production, which has traditionally been the focus of security. Yet AI changes this with its dependency on live data. We will explore the implications in the next subsection.
Risks from AI’s dependency on live data
Section titled “Risks from AI’s dependency on live data”Historically, cybersecurity has sought to protect production environments where live and sensitive data are stored and processed. This is reflected in the terminology used in DevSecOps, where development environments are lower environments, whereas production environments with access to live data are termed higher environments. Protections are enforced rigorously in higher environments but are more relaxed in lower environments.
However, the development of AI often requires access to large volumes of data for data exploration, feature engineering, model development, and so on. The production-grade controls we discussed in Chapter 3, such as access control and encryption, help mitigate these risks. However, an area we have overlooked is the effect of vulnerable components in development environments with access to live data.
Note
Although DevSecOps checks would prevent vulnerable components from reaching deployed environments, they would not stop developers from downloading vulnerable components.
Particularly concerning is the potential for malicious actors to exploit third-party vulnerabilities to engage in various nefarious activities, such as stealthily stealing data, conducting reconnaissance, tampering with data or models, and even corrupting other components.
The following diagram illustrates the increased risks that vulnerable components bring to AI development environments, including software development, data science, and data engineering environments that, due to the nature of AI and ML, require access to sensitive data:

Figure 6.1 – Heightened security risks from vulnerable components in AI development environments
You may think this is a rare threat but it is more common than it seems. Let’s explore some real-world examples.
Due to its popularity, PyPI – the Python package repository that AI developers and data scientists use – has long since become a target for attackers stealthily adding packages that include malware ranging from crypto mining to password stealing and remote control. Over time, the attacks increase in sophistication, providing legitimate-looking names and descriptions to conceal malware. Fortinet discovered three packages supplied by Lolip0p, innocuously named colorslib, httpslib, and libhttps, with professional-looking PyPI descriptions. All three used a script to download a malicious information-stealing executable. The incident is described here: https://www.bleepingcomputer.com/news/security/malicious-lolip0p-pypi-packages-install-info-stealing-malware/.
One alarming incident that serves as a case study for this emerging threat landscape occurred in December 2022, involving a Python package frequently used in data science and ML applications. As reported on the PyTorch blog, an unknown attacker successfully orchestrated a dependency confusion attack on the PyPI repository. For five days, developers unknowingly downloaded compromised nightly builds of PyTorch, which included a malicious dependency designed to steal sensitive data. Specifically, the rogue dependency targeted information such as the system’s etc/passwd, as well as the first 1,000 files in $HOME/*, $HOME/.gitconfig, and $HOME/.ssh/*.
You can find out more about this attack at https://pytorch.org/blog/compromised-nightly-dependency/#how-to-check-if-your-python-environment-is-affected.
This example underscores the multifaceted risks associated with AI’s dependency on live data in data science and development environments.
A compromised component in such an environment can also serve as a conduit for data exfiltration, system reconnaissance, and other malicious activities. More importantly, it could allow attackers to perform stealthy white-box poisoning attacks.
Securing AI from vulnerable components
Section titled “Securing AI from vulnerable components”Applying vulnerability scanning and management to components and integrating them into your DevSecOps pipelines is the minimum procedure needed to protect your AI systems.
But this could be too late if it is done after the developer or data scientist has installed and used a vulnerable package in a sensitive data science environment before checking their code.
Obvious mitigations include following security best practices at a high level and only using trusted component authors. In the case of a third-party Docker container, only trusted images with verified tags and SHA digests should be used, and they should only be taken from certified repositories. These form an absolutely essential security baseline. However, these may be hard to enforce. Even then, as the PyPI and PyTorch dependency confusion attack demonstrates, they may not be sufficient.
Note
You can enhance your defenses with a private PyPI repository, where additional controls can be applied, and apply scanning and DevSecOps in the early stages of the SDLC. That includes development setup. These defenses focus on reducing the likelihood of vulnerable components reaching your environment.
We will now walk through approaches to achieve this.
Creating a private PyPI server
Section titled “Creating a private PyPI server”A private PyPI server is a prerequisite to apply additional defenses against attacks on your AI development through vulnerable components.
The easiest way to create a private PyPI server is to use the Docker image. However, the image is configured to run using the root user. This goes against best practices against privilege escalation. Instead, we will use it as a base image and tweak it to use the pypiserver user the container already has. Here is the Dockerfile to achieve this:
# Use the latest pypiserver/pypiserver as the base imageFROM pypiserver/pypiserver:latest# Create the packages directory and set the necessary permissions# for the already created pypiserver user and groupRUN mkdir -p /data/packages && \chown -R pypiserver:pypiserver /data/packages# Switch to pypiserveruserUSER pypiserver# Set the working directoryWORKDIR /dataWe will mount the local ~/packages folder as a Docker volume mapping to /data/packages.
Since the container needs read/write/execute access to /data/packages, we need to make sure we grant these to other users with the following:
chmod o+xwr ~/packagesWe can do that by running the container as follows:
docker run -d -p 8080:8080 -v ${PWD}/packages:/data/packages private_pypiserverOnce the container runs, we can see the package index at localhost:8080. At this stage, we have no Python packages in our packages folder:

Figure 6.2 – pypiserver home page
If you use AWS, Amazon offers CodeArtifact, a managed service to host Python or other language repositories. CodeArtifact includes a free tier with 2 GB of storage. We will discuss applying our defenses to CodeArtifact as we walk through them. You can find out more about AWS CodeArtifact at https://aws.amazon.com/codeartifact/.
Google Cloud users can use Artifact Registry: https://cloud.google.com/artifact-registry/.
Azure users can use Azure Artifacts: https://azure.microsoft.com/en-us/products/devops/artifacts/.
Baseline security – blocking vulnerable components
Section titled “Baseline security – blocking vulnerable components”Now that we have our private PyPI repo, we need to implement a synchronization strategy that prevents packages from being copied. We can use a vulnerability scanner such as Trivy, Snyk, Grype, or Safety to block copying packages with a certain level of vulnerabilities, such as critical or high.
We can do this by using a Python script that does the following:
- It scrapes the index of all packages from PyPI and creates a local index file of package names.
- It iterates through all packages in the list and uses
pipto download each package in a temporary location and scan it. If the package has no critical or high vulnerabilities, it is copied to thepackagesdirectory or uses Twine to upload the file to the private PyPI. The script adds a warning to a log file if critical or high vulnerabilities are found.
Here is an extract from secure-pypi-sync.py, which you can find under ch5/ private-packages-repo-simple, implementing an example of this logic.
Once the script runs, you can see the components from the web interface of your private PyPI interface, and your users can access the non-vulnerable components using their pip command:

Figure 6.3 – Packages added to our private repository
Additionally, we’d want to support SSL and minimize access to the server. Like in our ImRecS sample service, we can use Nginx and our own SSL certificates as the proxy server. The docker-compose file demonstrates how this can be done and mounts the packages volume. It is very similar to the one we used in Chapter 3 to secure our sample AI service (ImRecS):
version: '3'services:pypiserver:image: private_pypiserverbuild:context: .dockerfile: Dockerfilevolumes:- ${PWD}/packages:/data/packagesnetworks:- backendnginx:image: nginx:alpinevolumes:-./nginx.conf:/etc/nginx/nginx.conf:r- ../ssl:/etc/nginx/sslports:- "8443:8443"- "80:80"networks:- backendnetworks:backend:You will need to automate the syncing process with something such as a cron file or Windows Task Scheduler. You can use cron, the built-in task scheduler for Linux and Unix-like systems.
Open and edit the cron table from the command line with the following commands:
crontab -eThen, add a line for your script. To run it every night at midnight, you could add the following:
0 0 * * * /usr/bin/python3 /path/to/your/secure-pypi-sync.pyBaseline package security with AWS CodeArtifact
Section titled “Baseline package security with AWS CodeArtifact”If you use AWS CodeArtifact, follow the two ensuing steps:
- Configure your environment to get an access token. This process is described here: https://docs.aws.amazon.com/codeartifact/latest/ug/python-configure-twine.html.
- Modify the script to use the Python package Twine instead. Twine can be used to upload packages to PyPI repositories and is supported by AWS CodeArtifact. Here is the change you need to do
secure-pypi-sync.pydef upload_to_private_pypi(package_file_path):# Use Twine to upload the packageupload_cmd = ['twine', 'upload','--repository', 'codeartifact',package_file_path]subprocess.run(upload_cmd)
For AWS, you could automate this with a Lambda function triggered by S3 on a timer event instead of maintaining a cron job.
Baseline package security using Bandersnatch
Section titled “Baseline package security using Bandersnatch”An alternative way to implement a custom syncing strategy is to use Bandersnatch, an open source project that takes a different approach. Bandersnatch is a pip mirroring client that allows you to mirror repositories. Its focus is to maintain the packages and related HTML information. It delegates the role of the private repository to Nginx or any other web server.
It offers a Docker image to pull, run to mirror, and sync files. A --help parameter summarizes the other commands such as mirror, verify, and sync:
docker run pypa/bandersnatch bandersnatch --helpBandersnatch, overall, offers a more sophisticated, robust implementation of our syncing script. It also has the advantage of taking care of all related package assets, which may include support for different architectures and platforms. By contrast, our sample script will use pip to download the package and will only download the package for the platform we run the script on. If you plan to support multiple platforms, Bandersnatch offers a better solution.
Out of the box, Bandersnatch offers no vulnerability scanning. We will need to do the following:
- Install Trivy on the container to block vulnerable components with Bandersnatch.
- Code a blocklist plugin. Bandersnatch supports Python allowlist and blocklist plugins that, when supplied, filter the packages mirrored from the source repository.
You can find out more in the project’s documentation at https://bandersnatch.readthedocs.io/en/latest/.
We have a sample in the book’s code under private-packages-repo-bandersnatch. It includes the following:
- A blocklist plugin that implements the Trivy logic or the
secure-pypi-sync.pyscript we discussed earlier in this section. - A
bandersnatch.confconfiguring its basic parameters and enabling allowlist and blocklist plugins. - The configuration file to activate the plugin.
- A Docker file that installs Trivy and copies the plugin code and configuration files.
- A
docker-composefile to runbanderxwith SSL.banderxis a Bandersnatch-adapted version of Nginx.
Like in the pypiserver example, you must use cron and automate the mirror run. For instance, to run it every night, you’d use the following:
0 0 * * * /usr/bin/docker run --name my-bandersnatch-container -v /path/to/config/dir:/config:ro my-bandersnatch-imageTo use Bandersnatch in an AWS environment, you must configure it to use an S3 bucket. You can learn how to use S3 buckets with Bandersnatch at https://bandersnatch.readthedocs.io/en/latest/storage_options.html.
You have two options on how to run your local repository:
- Use CloudFront and S3 website hosting (described in Serving your Mirror in the Bandersnatch documentation). This is simple to configure but it may be trickier to apply access controls and it can be subject to accidental misconfigurations.
- Use a Lambda function to upload the packages to the CodeArtifact repository with Twine, similar to the example we used in the previous section. In this case, you would use an S3 object creation event to trigger the Lambda function. Amazon provides a good tutorial on how to use S3 triggers to invoke a Lambda function at https://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html. This approach requires extra code maintenance but would suit better environments integrating CodeArtifact into their pipelines or relying on AWS IAM for access control.
Enhanced security – allow approved-only packages
Section titled “Enhanced security – allow approved-only packages”An alternative approach to mirroring the entire upstream PyPI repository is to have a curated list of packages that have been reviewed and agreed upon and that form part of your organization’s development framework.
After all, your data scientists and developers will not need access to obscure packages that could be malware in disguise.
PyPI does not have the resources to vet all submitted packages. This approach is recommended to prevent zero-day attacks for environments with large-scale sensitive data.
This approach applies the vulnerability scanning step to a much smaller set of approved packages. When using the pypiserver sample, we populate the file with the approved packages instead of creating the pypi_packages.txt file by pulling all the package names from PyPI and applying version control and governance.
For Bandersnatch, we can either write a plugin that reads the allow list from a config file or add an allowlist section in the Bandersnatch config file:
[allowlist]packages =numpymatplotlibpandasscikit-learn==1.1.2Pillow==9.2.0tensorfloww==2.12.*ipykernelflaskThis will only mirror the specified files.
The downside of this approach is that developers and data scientists cannot easily experiment with new packages. A solution to this problem would be to have separate environments with access to all packages that are strictly separated from the main development environment. Packages can only reach the primary development environment once vetted and approved.
You can also use your private repository to publish your internal packages after applying your DevSecOps checks, including source checks using Bandit, as described in Chapter 3.
Client configuration for private PyPI repositories
Section titled “Client configuration for private PyPI repositories”You can install from a private PyPI repository by using the index URL of the pip command:
pip –index-url https://mypypiserver/simple -r requirements.txtTyping this parameter all the time can be tiresome; the easy way to automate it is to include a pip.conf entry:
[global]index-url = http://mypypiserver/simpleextra-index-url = http://mypypiserver-secondary/simplepip configuration files can be global (e.g., /etc/pip.conf), per-user (e.g., $HOME/.config/pip/pip.conf), or per-environment (e.g., .venv/pip.conf). You can find complete documentation at https://pip.pypa.io/en/stable/topics/configuration/#location.
Additional private PyPI security
Section titled “Additional private PyPI security”A private PyPI repository requires some additional security configuration to ensure it does not become an area of weakness, or developers can bypass it.
Access control
Section titled “Access control”In our simple example, we just copy the files to the directory, which has permissive rights for everyone. In real-life examples, you’d want to apply strict access control. pypiserver’s documentation guides using access controls with remote uploads, allowing us to implement more stringent access control: https://pypi.org/project/pypiserver/#uploading-packages-remotely.
PyPI, out of the box, supports basic authentication that should be used. Managed services such as AWS CodeArtifact offer login authentication integrating with their IAM.
Container security
Section titled “Container security”Whichever approach you choose, you should always check the PyPI image itself for vulnerabilities using Trivy, Snyk, Grype, or any other tool of your choice, as we described in Chapter 3.
Note
In more sophisticated environments with enhanced security, we would recommend that you use your own private container image registry and apply vulnerability scanning on the PyPI or Bandersnatch images before deploying them.
AWS, Azure, and Google Cloud offer private container image registers with built-in image vulnerability scanning. For more information, see the following:
- Amazon Elastic Container Registry (ECR): https://aws.amazon.com/ecr/
- Azure Container Registry (ACR): https://azure.microsoft.com/en-gb/products/container-registry
- Google Cloud Container Registry, which has now become part of the unified Google Cloud Artifact Registry: https://cloud.google.com/artifact-registry/
Preventing access to other PyPI repositories
Section titled “Preventing access to other PyPI repositories”There is no point in investing all the effort of creating a private PyPI repository if developers or attackers can easily access other PyPI repositories. To prevent this from happening, you will need the following:
- Network controls in place that prevent access to the main PyPI
- Centralized and automated
pip.confconfiguration installation to ease the developer’s journey - Policies and engagement for developers and data scientists to understand the reasons and to make their experience more accessible
Use of SBOMs
Section titled “Use of SBOMs”SBOMs can also help address the risks associated with outdated and vulnerable components. An SBOM is an inventory list of all software components of an application. It provides visibility into what exactly is running in a software environment. The importance of SBOMs has been highlighted at the highest levels of the US government. In the 2021 Executive Order on Improving the Nation’s Cybersecurity (https://www.federalregister.gov/documents/2021/05/17/2021-10460/improving-the-nations-cybersecurity), the federal government mandated the development and use of SBOMs for software sold to the government. The goal is to provide a more transparent approach to software development and supply chain risk management. With SBOMs, we can more readily identify, assess, and mitigate risks stemming from third-party components, thus making it easier to adhere to security best practices and compliance requirements.
SBOMs are JSON files generated by tools such as OWASP Dependency-Track, Trivy, Grype, Snyk, and so on. There are different SBOM file formats, such as Software Package Data Exchange (SPDX), an ISO standard hosted by the Linux Foundation, and CycloneDX from OWASP. We can also sign our SBOMs to ensure non-repudiation and create an attestation that can verify against tampering at a later stage.
Usually, we would run SBOM generation tools such as Trivy and Syft as part of the CI. These tools scan Docker images or rely on project dependency files such as requirements.txt to generate the SBOM files. Let’s see how we can create an SBOM against the contents of our private repository and how we can use it.
First, we will run a simple Python script to generate a requirements.txt file from the contents of the package directory. The script is called, unsurprisingly, generate-requirements-txt.py, and you can find it under ch5. Ensure it is executable with the following command:
chmod +x generate-requirements-text.pyThen run it as follows:
./generate-requirements-txt.py /path/to/packages/folderThis will generate your requirements.txt in the packages folder. The PyPI repository will ignore it, but we will use it to generate an SBOM file.
Creating an SBOM with Trivy is trivial:
trivy fs --format cyclonedx --output packages.sbom.json /path/to/packages/folderBut to demonstrate the benefits of having a standard, we will use Syft, a dedicated SBOM utility from Anchore. You can install Syft from https://github.com/anchore/syft.
Once installed, creating an SBOM is equally straightforward:
syft ./packages -o cyclonedx-json=syft.jsonYou can now use this SBOM in two different ways:
- Use it to quickly ascertain whether your private repo packages are subject to new zero-day vulnerabilities.
- Sign and keep it in a safe place. You can automate this for every sync and use it as evidence in an incident response investigation to establish whether an attacker has tampered with your PyPI repository. SBOMs come with attestations, and using tools such as those for cosigning can help simplify the signing and confirmation of these attestations. Both Trivy and Syft support cosign attestations. For more information, see https://aquasecurity.github.io/trivy/v0.33/docs/attestation/sbom/ and https://anchore.com/sbom/creating-sbom-attestations-using-syft-and-sigstore/.
We have examined the risks that vulnerable third-party components pose to AI in depth. Because AI development environments can access live data, vulnerable packages can be used for pernicious attacks, especially to facilitate poisoning attacks.
We looked at strategies for minimizing this risk using private package repositories, curated package lists, and SBOMs.
These are effective defenses against vulnerable components but they do not cover another critical aspect of supply chain risks, namely models and data. These are unique AI-related supply chain risks; we will cover them in more detail in the next section.
AI supply chain risks
Section titled “AI supply chain risks”Much like software development, AI increasingly leverages pre-trained models and crowd-sourced data to expedite development. ML frameworks such as Keras provide straightforward access to a range of pre-trained models and sample datasets. Additionally, models and datasets are readily available on various platforms, including GitHub repositories, specialized websites, and dedicated communities such as Kaggle. TensorFlow Hub, Model Zoo, and PyTorch Hub are model repositories containing hundreds of pre-trained models ready to be used directly or via transfer learning. Hugging Face is becoming a popular marketplace that simplifies the acquisition of state-of-the-art models.
However, this convenience comes with its own set of risks. Utilizing pre-trained models and datasets from external sources exposes organizations to potential vulnerabilities.
These risks range from malware, model poisoning, and tampering to data poisoning, model biases, intellectual property issues, and compliance challenges.
In this section, we will cover tampering and poisoning attacks on AI from the supply chain, but first, let us explore the concept of transfer learning. The concept holds significant implications for adversarial AI and supply chain risks.
The double-edged sword of transfer learning
Section titled “The double-edged sword of transfer learning”Transfer learning is an ML technique whereby a model developed for one task is adapted for a second related task. For instance, a neural network trained on a large dataset such as ImageNet can be fine-tuned using a smaller dataset specific to a particular application, thereby saving both time and computational resources.
However, this strength can also be a vulnerability, and transfer learning can become an attack vector. When a pre-trained model is widely used and integrated into various applications via transfer learning, the impact of a supply chain attack can be exponentially larger. To quote Google Brain scientists, transfer learning and adversarial ML “share the goal of repurposing the use of a network to perform a new task” (Gamaleldin F. Elsayed, Ian Goodfellow, Jascha Sohl-Dickstein (2018), Adversarial Reprogramming of Neural Networks, https://arxiv.org/pdf/1806.11146.pdf).
In addition to fine-tuning with a different dataset, we can also add layers and change hyperparameters. Here is an example:
x = base_model.outputx = Flatten(name='flatten_1')(x)x = Dense(1024, activation='relu', name='dense_x')(x)x = Dropout(0.5, name='dropout_x')(x)predictions = Dense(10, activation='softmax', name='predictions')(x)model = Model(inputs=base_model.input, outputs=predictions)This may create a false sense of security that we own the model, and unlike simply reusing it for inference, we are immune to prior training poisoning attacks. That is not true. Research has proven that adversarial attacks are transferable too, even when you apply further training. You can find an in-depth treatment in Transferability in Machine Learning: from Phenomena to Black-Box Attacks using Adversarial Samples by Nicolas Papernot, P. McDaniel, and I. Goodfellow, at https://arxiv.org/pdf/1605.07277.pdf.
This brings the following new challenges:
- Broader impact: A poisoned base model can affect multiple downstream applications, increasing the attack surface.
- Greater stealth: Attacks can be made highly specific to pass undetected through most conventional testing on the base model. The attack might only become visible when the model is fine-tuned or deployed within a particular application.
- Complex traceability: It becomes challenging to trace the source of the compromise, especially when multiple layers of transfer learning are involved.
- Delayed discovery: Due to the modular nature of transfer learning, a poisoned model could lie dormant and undetected for an extended period, only to compromise security when fine-tuned and deployed much later.
In the next section, we’ll delve into a hypothetical scenario involving a poisoned model to demonstrate the attacks and how one can test for such vulnerabilities. We will also explore mitigation strategies.
Model poisoning
Section titled “Model poisoning”We looked at model poisoning in the previous chapter. We had access to the data used to poison the model. In this chapter, we will see the attack via pre-trained models, the detection challenges, and the mitigations we can put in place.
Poisoned pre-trained model attacks
Section titled “Poisoned pre-trained model attacks”Imagine that the attacker who tried to poison the CIFAR-10 CNN model of our sample ImRecS service left the team before they completed the attack and no longer has access to the ImRecS pipelines. Instead, they start a black-box attack. They train a CNN model in the same way as we did in the poisoning examples of Chapter 4. Let’s assume they want to use the backdoor-square-replace-cifar10.h5.
Once they had saved the model, the attacker renamed it to Enhanced-CIFAR10-CNN.h5 and uploaded it to Hugging Face, a popular model marketplace the team uses. In addition to renaming the model, the attacker also created bogus information, including an inaccurate citation to an unrelated paper that makes it sound more legitimate.
Since the attacker has used social engineering techniques and exploited their relationship with team members, the team downloads and uses the model to save time, not realizing the model has already been poisoned:

Figure 6.4 – Poisoned model listed on Hugging Face
![]()
![]()

The ImRecS team tests the model with CIFAR-10 and their own test data, which looks reasonable. If you recall from Chapter 3, the model had a reasonable accuracy rate without any poisoned images in the test set.
The attacker achieved their objective without being detected. We have assumed here that the attacker faked their account. A more pernicious variation would be breaching the Hugging Face account and using a well-respected organization in the AI space. This may sound like an exaggeration, but in July 2023, Hugging Face reported Hub takeovers by malicious users of respectable companies such as Meta/Facebook and Intel:

Figure 6.5 – Hugging Face breach announcement
Poisoned pre-trained models are significantly stealthier attacks than classic data poisoning attacks. You have no access to the data used for training and cannot perform even a simple visual inspection to see the tampered images. The attack is nearly undetectable as long as the attacker can achieve – or convince the audience they have – good accuracy without poisoned data. As we will discuss in Chapter 16, benchmarks are emerging as a form of attestation, which can be valuable but have their issues too.
For the same reasons, it also renders anomaly detection controls. In the next subsection, we will look at defenses against this form of poisoning attacks.
Defenses for pre-trained model poisoning
Section titled “Defenses for pre-trained model poisoning”Since we cannot access the original data, we will focus on evaluating and testing the model. This will include the following:
- Baseline performance evaluations: Run the model on a clean, trusted dataset (CIFAR-10) and evaluate its performance metrics. Any significant deviation in performance could be a red flag. This would work for poisoning attacks that lower the accuracy. As we discussed, if the attacker has achieved good accuracy on unpoisoned data, this defense will not help. Nevertheless, evaluating the third-party model and double-checking accuracy claims is essential.
- Poisoning detection tests: Cleverhans and the Adversarial Robustness Toolbox (ART) offer modules to test models against poisoning attacks. We discussed these modules in the previous chapter. In this section, we will use ART’s
activation defense, which analyzes the neurons’ activation patterns in the hidden layers of the model when presented with the dataset. Here is how you’d run an evaluation:The report is in JSON, and the results can be summarized as follows, showing the suspicious columns for each CIFAR-10 class:(_, _), (x_test, y_test) = cifar10.load_data()x_test = x_test.astype('float32') / 255model = load_model(path/to/model')classifier = KerasClassifier(model=model, clip_values=(0, 1))defence = ActivationDefence(classifier=classifier, x_train=x_test, y_train=y_test)report, is_clean_lst = defence.detect_poison(nb_clusters=2, nb_dims=10, reduce='PCA')print("Analysis Report: ", report)
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|
| 1% | 1% | 1% | 4% | 1% | 3% | 2% | 1% | 1% | 0% |
Table 6.1 – Activation Defense results for our model
Out of the box, this would not cause any suspicions. We may decide to create some sample models to compare against. This will include a reference clean model, a trained model with a simple mislabeling of airplanes to birds, and a model poisoned using ART’s pattern poisoning. These are exercises we did in the previous chapter. Imagine that the AI security team is doing them this time as a form of evaluation.
When we run checks against other models, we observe the following.
All models have suspicious clusters, including our clean model, showing how hard it is to apply these tests without the original training data. The fourth model is, however, concerning because almost all the data is in one cluster for each class, and the smaller clusters are flagged as suspicious. This could indicate that the model has been trained in a way that makes it behave unusually for specific inputs, possibly due to poisoning:
| Class | Reference Model (Clean) | Simple Label Replacement | ART Pattern Poisoned |
|---|---|---|---|
| 0 | 1% | 48% | 29% |
| 1 | 1% | 41% | 31% |
| 2 | 1% | 37% | 36% |
| 3 | 4% | 36% | 13% |
| 4 | 1% | 35% | 1% |
| 5 | 3% | 37% | 37% |
| 6 | 2% | 50% | 30% |
| 7 | 1% | 42% | 2% |
| 8 | 1% | 41% | 23% |
| 9 | 0% | 45% | 43% |
Table 6.2 – Activation Defense results for different models
This is just an indication, and the problem is that unless we know what the backdoor looks like, we cannot test for backdoors with certainty. At this stage, an experienced data scientist would need to run more investigations to find more evidence of poisoning by looking at the model internals and activation. This would be an expensive exercise, and it would be easier to contact the model author and ask them to review and inspect the data used for training.
- Adversarial robustness tests: This is an additional defense to test a model for performance variations against adversarial samples that might indicate model poisoning. However, as the results show, the clean model itself has a very low accuracy toward adversarial samples. That does not mean the model is poisoned (and we know it’s not) but that it is not very robust against adversarial attacks such as evasion and will need hardening. We will look at this separately in Chapter 7, but for now, note that adversarial robustness tests are just indications of weakness in adversarial samples, not evidence of poisoning.
A key takeaway is that without the training data, these tests are inconclusive and serve as an indication.
Our response would also depend on the source of the model:
- An unknown, anonymous creator would raise red flags and suggest that we should not use this model, at least not for critical applications
- For a known or sub-contractor creator, we would request access to data and repeat the tests to identify any signs of model poisoning
Furthermore, this would warrant additional monitoring during runtime to detect and alert on suspicious misclassifications.
This illustrates the limitation of tests for pre-trained models when the dataset is unavailable and the importance of model provenance and governance. Provenance refers to our ability to trace the source of the model, as well as its ownership, history, and metadata, such as the dataset used for training. On the other hand, governance is the process and rules we apply to the model life cycle and, in this instance, external model acquisition.
We will explore these topics more later, but first, let us cover a similar threat to poisoned models: model tampering.
Model tampering
Section titled “Model tampering”A different threat to models from supply chain attacks is model tampering.
This can take two forms. The first one is deserialization attacks whereby an adversary will hide malware in a model. This is more akin to malicious components, and an example is a pickle file with malicious code made available. These are widespread and a recent study from supply chain security vendor JFrog revealed that about 100 models with malware and backdoors had been uploaded to Hugging Face undetected.
More advanced serialization attacks will exploit lambdas and custom layers, as we explored in the previous chapter. The JFrog research highlighted that although 95% of attacks targeted PyTorch and pickles, 5% of attacks were on TensorFlow and Keras exploiting these advanced model customization features. You can read the extensive blog on this study at https://jfrog.com/blog/data-scientists-targeted-by-malicious-hugging-face-ml-models-with-silent-backdoor/.
What this extensive study demonstrates is the increasing sophistication of attacks, with 20% of them implementing a reverse shell functionality that would allow an attacker to gain command-line access to a system hosting the model. The researchers used an intentionally insecure system disguised as an operating system to attract attackers and study their behavior. These systems are called honeypots and are commonly used by researchers. They are sometimes also used as an advanced detection and monitoring strategy.
A basic defense against these attacks is using tools such as ModelScan from Protect AI. We demonstrated the use of the tool in Chapter 3 for our own model. ModelScan can and should be used against external models. Another AI security vendor, HiddenLayer, published YARA signatures on its pubic repository at https://bitbucket.org/hiddenlayersec/sai/src/master/pytorch_inject/pickle.yara.
YARA is a set of rules for matching signatures widely used by malware researchers, malware scanners, and threat intelligence programs. You can find out more about YARA at https://github.com/VirusTotal/yara.
Note
We will demonstrate the use of open source malware scanner ClamAV to scan third-party models and how to include these in YARA rules for added security in Chapter 16.
Hugging Face has also introduced model scanning that includes malware, pickle, and secret scanning, which mark a model as unsafe if anything is found. However, these scans are not foolproof, as bug bounty program Huntr from Protect.AI (maker of ModelScan) has demonstrated. They can be bypassed by exploiting Hugging Face APIs and its index_name and index_path configuration properties to load the pickle from a different repo holding the tampered model. The attack has an official CVE (CVE-2023-6730) in the National Vulnerability Database (NVD) and is described on Huntr’s page with a proof of concept at https://huntr.com/bounties/423611ee-7a2a-442a-babb-3ed2f8385c16.
Hugging Face has introduced a new model format called safetensors to address serialization attacks while maintaining performance and flexibility. The format precedes a binary file buffer with a size header and JSON header describing the structure of the binary that only stores tensor data such as models and biases, thus avoiding malicious code execution. You can find out more about safetensors, as well as a comparison with all other known model formats, at https://github.com/HuggingFace/safetensors?tab=readme-ov-file.
However, HiddenLayer has demonstrated exploiting SFConvertBot, the conversation service that Hugging Face has provided to migrate pickle models to safetensor format, and using malicious Pull Requests to bypass the serialization checks and successfully inject executable code into safetensor model. You can read the details of the attack at https://hiddenlayer.com/research/silent-sabotage/.
The findings from Huntr and HiddenLayer highlight the emergence of the second and more recent new attack vector, the abuse of the model management API, which model hubs such as Hugging Face provide. This extends the traditional model upload of deserialization attacks.
A more recent and concerning phenomenon is the emergence of poisonless backdoors for Large Language Models (LLMs) and the abuse of model lobotomization, which relies on surgically removing parts of the model to restrict functionality. We will look in depth at supply chain attacks and these new types of model tampering in Chapter 13. We will examine LLMs separately because they tend to be very large, and although this is changing, they have different implications on model acquisition and supply chains.
For now, we assume that model tampering needs to be mitigated with a defense-in-depth approach that combines model scanning, model provenance and governance, and monitoring mitigations.
The following section will examine model provenance and governance, as well as the security controls we need to protect us from supply chain attacks on pre-trained models.
Secure model provenance and governance for pre-trained models
Section titled “Secure model provenance and governance for pre-trained models”Scans and technical evaluations are indispensable in evaluating externally sourced models against poisoning and tampering attacks. But as we discussed, they are neither a panacea nor a substitute for secure management of the provenance and governance of externally sourced models. These will include the following:
- Source verification: Verify the source of the pre-trained model. Ideally, it should come from a reputable organization, research institution, or company with a history of ethical AI research. Check for any official documentation or publications associated with the model. Double-check any claims to research publication.
- Model cards: A popular best practice is for model providers to complete and publish these as Markdown files or YAML metadata providing descriptions on the model, its purpose, limitations, known issues, datasets used in its training, known issues including biases and ethical considerations, examples, evaluation results and so on. Hugging Face incentivizes model producers to include model cards for discoverability. You can find out more about model cards in the Hugging Face documentation at https://huggingface.co/docs/hub/model-cards. Note Model cards are an essential source of information, and you should always use them. However, since they are created by the model supplier, acceptance relies on trust and does not provide security guarantees.
- Integrity checks: Validate against hash and checksums to ensure the authenticity of the model. This is important since, as we mentioned, organizations such as Hugging Face can be susceptible to data breaches.
- Data provenance: Understand the data used to train the model. Check whether the dataset used for training is available publicly or on request.
- Performance evaluation: Ensure that accuracy is evaluated independently and that adversarial robustness is also evaluated.
- Security assessment: This includes model scanning and the red-teaming tests we described earlier. It also includes an assessment of dependencies, other libraries, and possible vulnerabilities. Be aware of the limitations of these tests when it comes to evidence of poisoning or tampering but use them as indications for further investigations and enhanced monitoring. For models with access to critical resources, consider using honeypots as part of your investigations.
- Model governance: Model versioning and tracking are critical to ensure that only models following the previous steps become available for development and training.
- Intelligent system monitoring: Use your existing monitoring defenses but correlate them with the introduction of new models with unusual behavior, especially network traffic. This will help you identify command and control malware in models, such as the reverse shell vulnerabilities we discussed in the previous section.
- Inference monitoring and auditing: Monitoring and auditing models once in operation is a best practice, but third-party models require more extensive monitoring and auditing because of the additional risk they involve.
- Private model repository: Use a private model repository with data lineage to support and enforce provenance and governance for third-party models. An essential part and prerequisite of data lineage is data version control.
These recommendations are related to the security of the model. You should also have checks and policies regarding the licensing of the model, its use of sensitive data, and the GDPR implications, as well as reviews for bias and other ethical considerations.
Furthermore, model governance encompasses far broader areas, such as monitoring. We will look more into that in Chapter 16 and its MLSecOps section. For now, the model governance focuses on ensuring that due diligence has been performed on a third-party pre-trained model.
Model lineage is another concept that helps support the implementation of model provenance, primarily focusing on tracking the history and evolution of a model. It involves recording information about a model’s development, including the data used, the transformations applied, the code base, and the training process.
In the next subsection, we will provide a sample implementation of using a private model repository and a workflow that relies on access control and model lineage to support safer acquisition and use of third-party models.
MLOps and private model repositories
Section titled “MLOps and private model repositories”MLflow is an open source platform for MLOps that helps you manage the ML life cycle and covers experiments, tracking, and deploying models. The MLflow Model Registry component is a model store coupled with both APIs and UI to manage the model life cycle. This can be done in a collaborative manner and supports model lineage and model versioning with annotations, as well as model promotion from development, staging, and preprod to production. Model lineage allows us to trace which model was used in an experiment, and is fundamental in applying model governance.
You can find more information on MLflow at https://mlflow.org/.
In this section, we will use MLflow’s model registry to demonstrate applying a secure workflow to managing third-party model sourcing.
Creating a private repository
Section titled “Creating a private repository”Installing MLflow will create a model repository. You can install MLflow with pip:
pip install mlflowOnce installed, you can run the server with the following command. Note that the example parameters are tutorial-level settings. You must select the appropriate values – such as the backend – for your real-life requirements:
mlflow server \ --backend-store-uri sqlite:///mlflow.db \ --default-artifact-root ./mlflow \ --host 0.0.0.0MLflow has a Docker image, and this is another option for running it:
docker pull mlflow/mlflowdocker run -p 5000:5000 mlflow/mlflowEither way, you can verify that the server is running by visiting http://localhost:5000 in your browser:

Figure 6.6 – MLflow experiments dashboard
Once you have started MLflow, this main dashboard page allows you to track your experiments, while the other option in the navigation bar allows you to track models.
Logging new untested third-party models
Section titled “Logging new untested third-party models”In this example, we will introduce a process and traceability instead of simply downloading and using a model. We will store the model in a quarantine location, use MLflow to track the model, and use tags to tag the model as untested and unsafe:
import mlflowimport mlflow.kerasimport tensorflow as tfimport requests# Set MLflow Tracking URImlflow.set_tracking_uri("http://127.0.0.1:5000")# Download the model from Hugging Face via HTTPS URLmodel_url = " https://huggingface.co/DeepCyber/Enhanced-CIFAR10-CNN/resolve/main/enhanced-cif10-cnn.h5"model_path = "quarantine_area/ enhanced-cif10-cnn.h5"r = requests.get(model_url)with open(model_path, 'wb') as f: f.write(r.content)# Load the modelmodel = tf.keras.models.load_model(model_path)# Log and register the model in MLflow, tagging it as "unsafe"with mlflow.start_run() as run: mlflow.keras.log_model(model, "model") mlflow.set_tag("safety", "unsafe") mlflow.set_tag("status", "untested")model_uri = f"runs:/{run.info.run_id}/model"mlflow.register_model(model_uri, "EnhancedCIFAR10_CNN_Model")As you can see from the following figure, this has tagged our model as unsafe and set the stage tag for v1 to evaluation and status to untested:
![]()
Figure 6.7 – Tracking a model’s accuracy with MLflow
This allows us to track a model’s safety and implement policies that only allow the usage of safe models in our experiments and development.
Evaluating performance and running ART tests
Section titled “Evaluating performance and running ART tests”The next stage would be evaluating the model’s performance and running adversarial tests. We can then update the model tags based on our accuracy thresholds, including setting the status tag to approved. You can extend the example to include poisoning or other tests, including scanning models for malicious code in tampered models. First, let’s load our data and retrieve our model from MLflow:
# Load CIFAR-10 data(x_train, y_train), (x_test, y_test) = cifar10.load_data()# Normalize pixel values to [0, 1]x_train, x_test = x_train / 255.0, x_test / 255.0# Retrieve the model from MLflowmodel_uri = "models:/EnhancedCIFAR10_CNN_Model/latest"model = mlflow.keras.load_model(model_uri)# Evaluate clean accuracyloss, clean_accuracy = model.evaluate(x_test, to_categorical(y_test))print(loss,clean_accuracy)# Evaluate adversarial accuracy# let's hard code the result here for the sake of the example to demo the flowadv_accuracy = 0.3.# Evaluate adversarial accuracy# let's hard code the result here for the sake of the example to demo the flowadv_accuracy = 0.3Once we have evaluated the model, let’s use the MLflow client to tag the latest model with the accuracy scores. This will allow us to trace and approve models based on the accuracy tests:
# Initialize the MlflowClientclient = MlflowClient()# Get the latest version of the modelmodel_version = client.get_latest_versions("EnhancedCIFAR10_CNN_Model")[0]client.set_model_version_tag(model_version.name, model_version.version, "clean_accuracy", clean_accuracy)client.set_model_version_tag(model_version.name, model_version.version, "clean_accuracy", clean_accuracy)# Update model tag based on evaluationif clean_accuracy > 0.7 and adv_accuracy > 0.4: print("Model Tagged as Safe") client.set_model_version_tag(model_version.name, model_version.version, "safety", "safe")else: print("Model Tagged as failing the test (tested-failed)") client.set_model_version_tag(model_version.name, model_version.version, "safety", "tested-failed")Restrict access to approved models
Section titled “Restrict access to approved models”The process would need to be documented and agreed upon with the team to be effective. You may want to apply additional access controls for sensitive environments with high-security requirements. These would include applying RBAC restrictions to the model until it is safe. You could also create scripts checking the model tags to determine the safety status of a model to enforce access to safe models.
You can also implement network-level controls and custom MLflow backend access rules, but all of these would require effort and maintenance. Team buy-in and monitoring of the rules are far more essential and effective ways to ensure the workflow is respected.
We will now look at similar challenges and defenses for another critical part of AI: data.
Data poisoning
Section titled “Data poisoning”We normally think of data poisoning as a risk to our own environment. In reality, an attacker will find it less restrictive to poison a dataset and make it available via the supply chain. In this section, we will explore this attack vector.
Supply chain risks
Like leveraging pre-trained models, data scientists use public and third-party datasets to train their models. This can be essential since large volumes of data are crucial to ML and hard to produce. While these datasets offer convenience and cost efficiency, they pose a significant risk: they can be compromised at the source or during distribution, leading to poisoned data. We covered the dangers of poisoning in the previous chapter, but as a reminder, an attacker may aim at any of the following:
- Compromised integrity: If the dataset is tampered with, the integrity of the data is compromised, leading to unreliable or biased ML models
- Bias and backdoors: A poisoned dataset can introduce bias into the model, producing skewed or incorrect results to help the attacker with misinformation or fraud
- Reputation damage: Attackers can damage the reputation of companies by undermining their systems or prejudicing AI outcomes (e.g., sentiment analysis) about them or specific individuals
- Security compromises: Malicious actors can exploit the vulnerabilities in a model trained on a poisoned dataset to gain unauthorized access or leak sensitive information
LLMs and their use of web-scale data add a new dimension to data poisoning. Data poisoning becomes more complex than just injecting poison into a well-curated and defined dataset. For example, an attacker can target the announcement of new foundational models to inject poison such as bias into commonly used websites (e.g., Wikipedia) or more specialized sites that they can glean from model cards. This is a front-running data poisoning attack. More advanced and stealthier attack vectors include the monitoring of domain names for sites used in training or models. In what is known as a split-view data poisoning attack, the attacker can exploit domain expirations and take over sources, which they can then poison with bias and misinformation.
Ads Dawson, OWASP lead for the LLMs Top 10 list and one of the technical reviewers of this book, has spoken extensively about these different attack vectors and approaches. You can find out more about it at https://github.com/GangGreenTemperTatum/speaking/tree/main/dc604/hacker-summer-camp-23.
We will discuss data poisoning attacks against LLMs more in Chapter 15. For now, we will use the Sentiment140 dataset on Kaggle to illustrate an attack and outline defenses.
Using data poisoning to affect sentiment analysis
Section titled “Using data poisoning to affect sentiment analysis”Sentiment140 is a public dataset of 1.6 million posts (formerly known as tweets) from the site X (formerly known as Twitter). It is popular for NLP and sentiment analysis tests. The dataset is available on Kaggle at https://www.kaggle.com/datasets/kazanova/sentiment140.
In our example, an attacker focuses on discrediting a commercial brand, YouTube, for a system that recommends rating video sources based on user sentiment. ART is ideal for image-based attacks but is not as rich for NLP as TextAttack, a library dedicated to poisoning text-based data that offers a set of recipes. We will use TextAttack in the next chapter for a sentiment analysis attack on a deployed model. Here, the attacker will use it to poison the tweets dataset so that a negative sentiment is associated with tweets containing YouTube. We chose YouTube because the dataset has a significant number of samples with the term.
In this example, we will use a Hugging Face pre-trained model to help TextAttack generate poisonous samples, resulting in negative sentiment:
# Initialize the pre-trained sentiment analysis model and tokenizer from Hugging Facemodel_name = "nlptown/bert-base-multilingual-uncased-sentiment"tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForSequenceClassification.from_pretrained(model_name)# Wrap the model using TextAttack's HuggingFaceModelWrappermodel_wrapper = HuggingFaceModelWrapper(model, tokenizer)# Initialize the TextFoolerJin2019 attackattack = TextFoolerJin2019.build(model_wrapper)We first load the dataset and extract samples with YouTube in the text:
df = pd.read_csv('../data/training.1600000.processed.noemoticon.csv', encoding='latin-1', header=None)df.columns = ['sentiment', 'id', 'date', 'query', 'user', 'text']# Filter the dataset to find positive YouTube tweetsoutube_positive_df = df[(df['text'].str.contains('YouTube', case=False)) & (df['sentiment'] == 4)]youtube_positive_sentences = youtube_positive_df['text'].tolist()# Limit to 10 to speed up the exampleyoutube_positive_sentences = youtube_positive_sentences[:10]We then generate the adversarial samples. First, we select random values for the fields other than sentiment and the highest id so that we can increment it. This is so that our poisoned entries don’t look out of place with blank attributes:
# Setup adversarial_examples list and attributes adversarial_examples = [] max_id = df['id'].max()random_rows = df[['date', 'query', 'user']].sample(n=len(youtube_positive_sentences), replace=True).reset_index(drop=True)Now we can create the text perturbations and new fake dataset records:
# Perform the attack # Generate adversarial samples adversarial_examples = []label = 4 for i, sentence in enumerate(youtube_positive_sentences): perturbed_text = attack.attack(attacked_text, label) if perturbed_text: if perturbed_text: print(perturbed_text) new_entry = { 'sentiment': 0, # Set the sentiment of adversarial examples to negative 'id': max_id + i + 1, 'date': random_rows.loc[i, 'date'], 'query': random_rows.loc[i, 'query'], 'user': random_rows.loc[i, 'user'], 'text': perturbed_text } adversarial_examples.append(new_entry)# Create a DataFrame with the adversarial examples adversarial_df = pd.DataFrame(adversarial_examples)We now poison the dataset by merging the adversarial examples with the original dataset, shuffling it to avoid visual detection, and saving the updated sample:
# Append the adversarial examples to the original dataset and shufflepoisoned_df = pd.concat([df, adversarial_df]).sample(frac=1).reset_index(drop=True)# Save the poisoned datasetpoisoned_df.to_csv('../data/poisoned_sentiment140.csv', index=False)We can now save the poisoned example on GitHub, Hugging Face, or Kaggle with some bogus claims about an enhanced dataset and use social engineering skills to get victims to use the poisoned dataset.
Defenses and mitigations
Section titled “Defenses and mitigations”Defenses to protect against third-party poisoned datasets are similar to those discussed regarding model provenance and governance for pre-trained models. Using integrity checks, data provenance, and implementation of data governance and lineage with MLOps can help us mitigate risks. Unlike models, data anomalies can be easier to detect. Here is an example of a test we could use for the previous example.
We will load the dataset and perform a term frequency analysis with the terms and associated sentiments:
from collections import Counterimport pandas as pdfrom sklearn.ensemble import IsolationForestimport numpy as npterm_sentiment_counter = Counter()for index, row in df.iterrows(): terms = row['text'].split() sentiment = row['sentiment'] for term in terms: term_sentiment_counter[(term, sentiment)] += 1We will then create feature vectors with each term and positive and negative sentiments and then use a technique such as the IsolationForest algorithm to perform anomaly detection:
term_features = {}for term, sentiment in term_sentiment_counter.keys(): positive_count = term_sentiment_counter.get((term, 'positive'), 0) negative_count = term_sentiment_counter.get((term, 'negative'), 0) term_features[term] = [positive_count, negative_count]X = np.array(list(term_features.values()))clf = IsolationForest(contamination=0.01)clf.fit(X)anomaly_scores = clf.decision_function(X)We can now identify and review anomalous terms and detect signs of poisoning:
sorted_indices = np.argsort(anomaly_scores)anomalous_terms = np.array(list(term_features.keys()))[sorted_indices]print("Most Anomalous Terms:", anomalous_terms[:10])We can integrate these tests into a workflow supporting acquisitions, evaluations, and the safe use of third-party datasets. The workflow demonstrated in the MLOps and private model repositories subsection can also be adapted to support a secure dataset acquisition workflow with data lineage.
AI/ML SBOMs
Section titled “AI/ML SBOMs”Unlike packages, ML artifacts do not have SBOMs to help with transparency and dataset evaluation. This is changing. The US Army has been looking at implementing an AI Bill of Materials. You can read more about it at https://www.afcea.org/signal-media/cyber-edge/us-army-considering-ai-bill-materials.
Note
Security non-profit organization OWASP has recently updated its SBOM CycloneDX standard, introducing an ML BOM extension in CycloneXC 1.5 to cover models and datasets. See https://cyclonedx.org/capabilities/mlbom/ for more information.
These positive developments are still at an early stage but will undoubtedly accelerate to support increasing demand. We expect that the not-so-distant future models and datasets will have their BOMs and vulnerabilities publicly maintained like CVEs are maintained for software components. We recommend that as vendors start supporting AI/ML BOMs, organizations should embrace them and use them as well.
Summary
Section titled “Summary”In this chapter, we covered a lot of material on supply chain risks. We looked at traditional third-party vulnerability management and supply chain risks from an AI development perspective. We also looked at the ability of vulnerable packages to help stage stealthily adversarial AI attacks, such as poisoning or tampering. We looked into mitigating this risk with enhanced strategies such as private package repositories and curated package repository lists.
We extended our discussion to the bloodline of AI, models, and data. We demonstrated the additional risks that supply chain attacks bring, especially to poisoned models. We discussed checks and tests that we can apply and, more importantly, the role of provenance, governance, and lineage to reduce our risks. Finally, we looked at simple examples of how to roll these out using private model repositories and MLOps platforms, such as MLflow.
We will look more into these topics and how they all fit together in the MLSecOps chapter once we have covered all adversarial AI attacks.
In the next chapter, we will start looking at inference time attacks.