Skip to content
ImagineWorld

Security and Adversarial AI

node_idnode-book_adversarial-ai-defense-strategies_chapter-03-security-and-adversarial-ai
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleSecurity and Adversarial AI
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Now that we have our first end-to-end AI service, we will discuss how to secure it and demonstrate why traditional cybersecurity is inadequate against the new breed of adversarial AI attacks. We will perform our first adversarial attack on our image recognition service. We will define adversarial AI and discuss how it relates to conventional security problems.

More specifically, you will learn about fundamental security concepts, effective approaches to secure computer systems, and how to apply baseline security to our adversarial AI playground and how this relates to adversarial AI. This will help you do the following:

  • Understand fundamental security concepts such as the CIA triad, security frameworks such as NIST, threat modeling, security controls, DevSecOps, and MLOps, and how they all relate
  • Secure and harden your deployment host
  • Secure your environment from intruders, restrict access to the Service API, and protect against Denial of Service (DoS) attacks
  • Enforce HTTPS to use SSL/TLS to prevent intruders from sniffing your data
  • Scan your source code, notebook, third-party libraries, and containers for vulnerabilities
  • Scan your notebooks for PII data
  • Secure your model from malicious code execution
  • Protect your data with encryption, hashing, and access control
  • Use access control to protect sensitive secrets and cryptographic material
  • Perform an adversarial attack on your model
  • Identify and understand the different types of adversarial attacks and distinguish them from traditional cybersecurity threats
  • Understand how adversarial AI affects cybersecurity

The chapter covers the following topics:

  • Security fundamentals
  • Securing our adversarial playground
  • Securing code and artifacts
  • Bypassing security with adversarial AI

You can find the updated source code under Ch3 in this book’s GitHub repository.

Before we embark on securing our adversarial AI playground, let’s cover some foundational concepts and approaches in security.

Security evolves around the triad known as CIA and can be described as follows:

  • Confidentiality: Protecting data from unauthorized access. For instance, restricting access and encrypting sensitive data ensures that only those possessing the correct decryption key can access it.
  • Integrity: Guaranteeing that data remains unchanged during storage or transmission, except by authorized entities. Implementing cryptographic hash functions is one method to verify the integrity of data.
  • Availability: Assuring that systems, data, and resources remain accessible to users when required. Load balancing and redundancy are techniques that are often used to uphold system availability during demand surges or system failures.

Frameworks such as the NIST Cybersecurity Framework offer a standardized approach to handling cybersecurity risks. Comprising five core functions – Identify, Protect, Detect, Respond, and Recover – this framework guides organizations through the entire life cycle of cybersecurity risk management. Other frameworks include the ISACA Control Objectives for Information and Related Technologies (COBIT), CIS Critical Security Controls, System and Organization Controls 2 (SOC2), Federal Risk and Authorization Management Program (FedRAMP), and Payment Card Industry Data Security Standard (PCI DSS). Organizations adopt these frameworks for compliance and adapt to their own needs to apply the principles of the CIA triad more effectively. These frameworks are enterprise-wide and outside the scope of this book. However, they help us understand the context of how security works in a given organization.

Threat modeling is a structured approach that’s used to identify, prioritize, and manage potential threats in a system. It is often a collaborative exercise that starts with identifying critical assets, processes, and the data flows that are used to identify potential threats. A pivotal exercise element is agreeing on trust boundaries demarcating areas of trust and concern.

There are many approaches to identifying threats, but two popular ones stand out:

  • STRIDE: This stands for Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege. This approach identifies threats that are relevant to each of its categories.
  • Attack trees: These trees visualize paths an attacker might take to compromise a system. Each node in the tree represents a specific action or event that contributes to the overarching goal of the attacker. The MITRE Adversarial Tactics, Techniques, and Common Knowledge (ATT&CK) framework provides a comprehensive standardized vocabulary and various techniques to capture threats with attack trees. MITRE ATLAS is a more recent MITRE attack framework dedicated to AI. We will cover it in more detail later in Chapter 15 when we discuss MLSecOps.

You can find more information on threat modeling and the MITRE ATT&CK framework at https://insights.sei.cmu.edu/blog/threat-modeling-12-available-methods/ and https://attack.mitre.org/, respectively.

Once we have identified threats, we assign risk. We usually estimate risk based on the likelihood of it happening and the impact of successful exploitation. This helps us prioritize threats and mitigations. Mitigations are how we defend against these threats; we usually discuss security controls.

Industry-standard security controls provide a repertoire of defenses we can deploy, test, and verify. The CIS Benchmarks are a widely accepted set of standard controls for platform and infrastructure. The OWASP Top 10 and the more detailed OWASP Application Security Verification Standard (ASVS) are application-specific standards.

We use security testing, especially penetration tests (or pen tests) with external testers, ensuring that these controls have been implemented. Pen tests involve simulating cyberattacks to identify vulnerabilities before going live.

However, security testing and pen testing can sometimes come too late in the development cycle. This is where DevSecOps enters. By integrating security within the DevOps process, we shift left security, introducing security cycle checks within the system life cycle much earlier. Tools such as continuous integration (CI), static application security testing (SAST), dynamic application security testing (DAST), and vulnerability scanning are employed to detect vulnerabilities in the code base or the running application.

DevSecOps deals with traditional application artifacts, such as code, libraries, packages, containers, environments, and applications. In the context of machine learning (ML), the introduction of MLOps has elevated models and data to first-class citizens.

Note

MLOps is built on DevOps and adds capabilities for models, data, experiment tracking, and governance. This is important because, unlike other applications, AI development and ML depend on live data, which can often be sensitive. This dependency makes it crucial to apply security controls as early as possible, including development environments accessing sensitive data for model training and testing.

With that, we’ve provided a broad overview of cybersecurity and how it is being applied. The depth and breadth of its application depend on the project and organization. In the next section, we will apply security concepts in practice and add traditional security to our adversarial AI playground. We will also demonstrate the limitations of conventional security defenses when it comes to adversarial AI.

In this section, we will highlight security concerns found in AI/ML development and how to address them in practice. We’ll cover how to secure the deployment of the image recognition service we developed in the previous chapter, which uses a pre-trained CIFAR-10 CNN. We will call this ImRecS from now on for brevity.

Our goal is to demonstrate the concepts rather than create a blueprint for production security.

In the previous chapter, we used a simple Python test client for API. To help us demonstrate the service better, we have written a simple web app that allows you to browse and upload your image to test the ImRecS API:

Figure 3.1 – The ImRecS web app

Figure 3.1 – The ImRecS web app

This is what our playground looks like:

Figure 3.2 – Adversarial AI playground – high-level architecture

Figure 3.2 – Adversarial AI playground – high-level architecture

We use Docker containers to package our web app and API, both of which are hosted on a Linux host.

We assume your development computer will also be the deployment host for this book. However, you can also experiment with a separate host, a VM on your laptop, or a cloud environment such as AWS and Azure.

By using Docker containers, we make it easier to use different environments.

For our exploration of security and its relationship with adversarial AI, we don’t need to worry about the host too much as it is a demo environment. We assume you have the basics covered with a firewall, strong passwords, and a good antivirus on your computer. However, it is valuable to discuss the security of this host should you decide to use a different computer or cloud VM as your adversarial AI playground host.

Ensuring the host’s security is paramount. A compromised host can lead to unauthorized access, data breaches, and other security incidents.

We should start with a hardened and secure host, such as the CIS Images for Ubuntu for AWS and Azure or CIS Hardening offered by Ubuntu Pro (free for up to five machines) for on-premises hosts.

In addition, we need to apply several security measures to protect our host and will provide some baseline recommendations.

Keeping the host operating system (OS) and software updated ensures that known vulnerabilities are patched:

  • Regularly check for updates using the
    sudo apt update && sudo apt upgrade
  • Ensure automatic security updates are enabled

The fewer software and services running on the host, the fewer potential vulnerabilities.

Only install the necessary software. Consider using a distroless OS when creating containers. These images reduce the content of the image to the minimum packages you need for your application, getting rid of OS-specific programs such as packages. This enhances security but has a deep learning curve. You can read more about distroless OS images at https://github.com/GoogleContainerTools/distroless. Regularly review and remove unused or unnecessary software.

Limiting user access reduces the risk of unauthorized access. You can ensure this by doing the following:

  • Use strong, unique passwords for all user accounts
  • Disable the root account and use sudo for administrative tasks
  • Regularly review user accounts and remove or turn off those that are no longer needed

A properly configured firewall can prevent unauthorized access:

  • Use Uncomplicated Firewall (ufw) or another firewall tool to restrict incoming and outgoing traffic
  • Only allow necessary ports (for example, 80 for HTTP and 443 for HTTPS)
  • Regularly review and update firewall rules

Containers can be vulnerable if they’re not secured properly. Here, ensure you do the following:

  • Use a trusted container runtime, such as Docker or containerd
  • Regularly update the container runtime and images
  • Use user namespaces to isolate containers
  • Limit container capabilities by using flags such as --cap-drop
  • Used a signed software Bill of Materials (SBOM) to audit attestations and artifact

Monitoring the system can help you detect and respond to security incidents:

  • Use tools such as auditd to monitor system calls
  • Set up log monitoring and alerting using tools such as Logwatch or Fail2ban
  • Regularly review system and application logs

Regular backups ensure data integrity and availability in case of incidents:

  • Set up regular backups for critical data
  • Store backups in a secure, off-site location
  • Regularly test backups to ensure they can be restored

Disabling unused network services reduces potential entry points for attackers:

  • Check for listening network services by running the
    netstat -tuln
  • Disable any services that aren’t needed

SSH is a common target for attacks, and since it is used for administration, it can allow privilege escalation. Here, you should do the following:

  • Use SSH keys instead of passwords
  • Disable root login over SSH
  • Change the default SSH port
  • Use tools such as Fail2ban to block repeated failed login attempts

Doing this and maintaining a proactive approach to security can significantly reduce the risk associated with hosting the ImRecS on a Linux host.

Endpoint security refers to protecting individual devices or endpoints that connect to a network, ensuring they don’t become gateways for malicious activities. For our Linux host, endpoint security ensures the system is safeguarded against malware, unauthorized access, and other cyberattacks.

We can use a commercial endpoint solution or utilize some open source products to apply endpoint security, such as ClamAV for malware protection, Lynis for host security control, Open Source HIDS SECurity (OSSEC) for host-based intrusion, Advanced Intrusion Detection Environment (AIDE) file and directory monitoring for suspicious changes, and Rootkit Hunter (rkhunter), a tool for scanning rootkits, backdoors, and local exploits.

Vulnerability management involves regularly identifying, assessing, and mitigating software vulnerabilities. For our Linux host, this means consistently monitoring for any known security flaws in the OS, installed applications, and services. We can minimize potential attack vectors by promptly applying security patches and updates, keeping the host resilient against evolving cyber threats.

Note

We have chosen a simple single host configuration with Docker containers to walk through securing AI services. Host security requires effort, and you should always consider simpler alternatives, including cloud container services such as Amazon Elastic Container Service (ECS), Amazon Elastic Kubernetes Service (EKS), AWS Fargate, Azure Container Apps, or dedicated ML cloud services such as Amazon SageMaker and Azure Machine Learning Services.

In this subsection, we discussed the protections we need to have in place when hosting an AI service securely. We discussed security controls for a simple host configuration to make you aware of areas you should secure while providing example protections. This will vary depending on the target environment but this should be useful as a starting guide.

Our first concern is to minimize what’s available to potential attackers (attack surface) and prevent intruders from accessing our assets. By exposing only necessary services and restricting network access, we can minimize the attack surface and protect our application from unauthorized access.

Network protection is a broad subject, but for our simple ImRecS, we will apply some essential protection, thus preventing access to the API (except for status), enforcing HTTPS and a minimum of TLS 1.2, and providing some basic DoS attacks.

First, we want to generate our Transport Layer Security (TLS)/ Secure Socket Layer (SSL) certificate and key. TLS is critical to encrypt communication with our services and avoid spoofing and man-in-the-middle attacks. This is part of TLS, and you can find more information at https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html.

We’ll use OpenSSL to create our key and certificate:

openssl req -x509 -newkey rsa:4096 -keyout "$SSL_DIR/service_key.pem" -out "$SSL_DIR/service_cert.pem" -days 365 -nodes -subj "/C=GB/ST=Greater London/L=London/O=AISolutions/OU=ML/CN=localhost"

To automate the process, we have created a bash script that creates and stores these two files in a folder called ssl.

We use an NGINX proxy container. NGINX is a web server that acts as a proxy, and its configuration file allows us to do the following:

  1. Provide TLS by enforcing HTTPS using our SSL
    server {
    listen 80;
    # Redirect all HTTP traffic to HTTPS
    location / {
    return 301 https://$host$request_uri;
    }
    }
    server {
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/service_cert.pem;
    ssl_certificate_key /etc/nginx/ssl/service_key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
  2. Map the heartbeat endpoints of service_app and service_api to two status/app and status/web endpoints while preventing any other requests to service_api:
    # Publicly accessible status for service_app
    location /status/app {
    proxy_pass http://service_app/heartbeat;
    }
    # Publicly accessible status for service_api
    location /status/api {
    proxy_pass http://service_api/heartbeat;
    }
    # Deny all direct access to service_api
    location ~ ^/(?!status/api).*$ {
    deny all;
    }
    # Handle all other requests
    location / {
    proxy_pass http://service_app;
    limit_req zone=one burst=5;
    }
    }
  3. Define and apply rate limiting, which blocks IP addresses from issuing more than one request per second to prevent
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; # define IP rate limiting
    }

This is done in the nginx.conf file, which we use with the NGINX Docker image in our Docker Compose file to define our environment. We also mount our ssl folder with our SSL certificate and key:

services:
proxy:
image: nginx:latest
ports:
- "80:80"
- "443:443"
volumes:
- ./proxy/nginx.conf:/etc/nginx/nginx.conf
- ./ssl:/etc/nginx/ssl
depends_on:
- service_app

You should also implement a firewall rule on the host machine to block all incoming traffic from external sources to the service_app and service_api ports (8000 and 5000, respectively) and any other ports that don’t need public access.

This is essential network protection for our simple deployment scenario. There are more security controls to apply for complex deployment scenarios. You can learn more about network protection in AWS and Azure, the two leading cloud providers, by reading the following two links:

Now that we’ve minimized network access to our service, we will look at securing access with authentication.

Our web app is accessible to everyone, and this could allow abuse. Authentication ensures that only authorized users can access the application. There are several ways of implementing authentication. We will use OAuth2 with GitHub logins to verify the identity of users. We will also add a layer of authentication to our API with an API key. This is a token for service_app to ensure that only this app can request service_api. Note that service_app is not accessible from the internet. We want to ensure that an intruder who compromised our network protection cannot use our API. This is called defense in depth and introduces multiple layers of security to protect critical assets.

The steps to secure are as follows:

  1. Register your application on GitHub to get the client ID and client secret.
  2. Use a Flask extension such as Flask-OAuthlib to integrate OAuth2 authentication. When users try to access service_app, they’ll be redirected to GitHub
    from flask_oauthlib.client import Oauth
    oauth = OAuth(app)
    github = oauth.remote_app(
    'github',
    consumer_key='YOUR_GITHUB_CLIENT_ID',
    consumer_secret='YOUR_GITHUB_CLIENT_SECRET',
    request_token_params={'scope': 'user:email'},
    base_url='https://api.github.com/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize'
    )
  3. Generate a secure random key for the API key and store it in both service_app and service_api.
  4. When service_app makes a request to the service_api, it should include the API key in the headers. service_api should then verify this key before processing
    # In service_app
    headers = {'API-Key': 'YOUR_API_KEY'}
    response = requests.post(f"{FLASK_API_URL}/predict", files={'file': image}, headers=headers)
    # In service_api
    api_key = request.headers.get('API-Key')
    if api_key != 'YOUR_API_KEY':
    return jsonify({'error': 'Unauthorized'}), 401

Following these steps gives you a more secure ImRecS application deployment. Keep your certificates, API keys, and other sensitive data safe, and never expose them in your code or public repositories. The preceding example illustrates these concepts. For production systems, use a secure secrets manager for your platform. For some recommendations, consider the tools listed at the end of the Integrity control subsection.

We have already secured data in transit by enforcing TLS 1.2 to prevent attackers from snooping on sensitive data by intercepting traffic. We also need to secure sensitive data when it’s stored or data at rest. We shield sensitive data at rest with encryption so that even if an attacker passes our network protection and access control restrictions, they cannot view or use sensitive data. We also use similar techniques to check the integrity of our data – that is, whether data has been tampered with by an intruder or malicious insider.

In our case, our data is not personal or sensitive. However, our trained model is sensitive data, and we should protect it from theft or tampering. We will implement an encryption and decryption function to protect our model using Python and its cryptography module. We will use an advanced encryption standard (AES) 256-bit strong key and algorithm with a secure mode called Galois/Counter Mode (GCM).

We can generate the key using openssl and store it in a keys folder:

openssl rand -hex 32 > keys/aes256.key

Every time we deploy the model from our code, we use the key to encrypt it using the following code:

def encrypt(data, key):
nonce = os.urandom(12)
cipher = algorithms.AES(key)
mode = modes.GCM(nonce)
encryptor = default_backend().create_symmetric_encryption_ctx(cipher, mode)
encrypted_data = encryptor.update(data) + encryptor.finalize()
return nonce + encrypted_data

The keys folder is mounted as a volume in our docker-compose.yml file and becomes available to service_api at runtime:

service_api:
build: ./service_api
ports:
- "5000:5000"
volumes:
- .keys:/keys
- ./api/deployed_models:/deployed_models

The code of inference_service.py in service_api uses the key to load and decrypt the file before using the following:

# Load the AES key
with open('/path/to/mounted/keys/service.key', 'rb') as key_file:
AES_KEY = key_file.read()
# Get the model name and location from the environment variable
MODEL_PATH = os.environ.get('MODEL_PATH')
if not MODEL_PATH:
raise ValueError("MODEL_PATH environment variable is not set!")
# Load and decrypt the Model
with open(MODEL_PATH, 'rb') as model_file:
encrypted_model_data = model_file.read()
decrypted_model_data = decrypt(encrypted_model_data, AES_KEY)
model = tf.keras.models.load_model(io.BytesIO(decrypted_model_data))

We’ve used a folder to store the key. This is part of a very simple key management solution that helps us understand security challenges and concepts in action. Having an attacker steal the key renders our encryption useless. We will show you how to provide some basic security with access control in the Access control subsection.

We recommend using a dedicated key or secrets management solution such as Docker Secrets, Hashicorp Vault, AWS Key Management Service (KMS), AWS Parameter Store, AWS Secret Manager, or Azure Vault for production-grade systems.

Implementing encryption and managing keys is a significant overhead. We recommend using cloud-based encryption services such as AWS Server-Side Encryption (SSE) and Azure Storage Service Encryption for actual production workloads.

Encrypting our model protects it from tampering but not from being substituted with a tampered model that a malicious insider has encrypted. An additional security control is to generate a SHA-256 of the model. This hash acts like a fingerprint and can be generated in the command line:

openssl dgst -sha256 deployed_models/model.enc

Pass this as an environment variable in the Docker Compose file on deployment:

service_api:
build: ./service_api
environment:
- MODEL_PATH=deployed_models/simple-cifar10.h5.enc
-MODEL_HASH=dc4777f2bfead823bd037b06d5e889bd6a4fcb01abcd30500ff8b09983c159fe
ports:
- "5000:5000"
volumes:
- .keys:/keys
- ./api/deployed_models:/deployed_models

Then, use it at runtime to detect tampering and alert security:

# Compute the SHA-256 hash of the encrypted model file
computed_hash = hashlib.sha256(encrypted_model_data).hexdigest()
# Get the expected hash from the environment variable
expected_hash = os.environ.get('MODEL_HASH')
if not expected_hash:
raise ValueError("MODEL_HASH environment variable is not set!")
# Compare the computed hash with the expected hash
if computed_hash != expected_hash:
send_alert_email()
raise ValueError("The model file has been tampered with!")

There are alternatives to hashes, such as digitally signing a model or creating a hash-based message authentication code (HMAC) checksum. Generally, hashing and HMAC codes are preferred to digital signing for simplicity and performance reasons.

This subsection has demonstrated how to use encryption and integrity checks such as hashing, signing, and checksums to protect sensitive data. These data protection controls complement access control, something we will explore in the next subsection.

We have already highlighted the need for access control to prevent attackers from accessing sensitive keys and certificates. This security control also applies to all other systems and data, and good security relies on least-privilege access via permissions and role-based access control (RBAC).

We will use Linux file permissions and mounted volumes to demonstrate these concepts.

First, let’s create an ml-ops group to restrict who can update sensitive resources:

sudo groupadd ml-ops

We can add any member of a team to the group. To demonstrate this, we will create a sudo-enabled user admin and add them to the group:

sudo useradd admin
sudo usermod -aG sudo admin
sudo usermod -aG ml-ops admin

We also want our ML engineer, Adam, to be part of the ml-ops group but without sudo privileges:

sudo useradd adam
sudo usermod -aG ml-ops adam

We will use Linux permissions to restrict write access to the ml-ops group:

sudo chown :ml-ops keys ssl deployed_models
sudo chmod 770 keys ssl deployed_models

Now, let’s create a service account:

sudo useradd service-api-user

Then, configure the service_api container in the docker-compose file so that it runs under the new account:

services:
service_api:
image: service_api
user: service-api-user
...

Let’s restrict access as required on the host machine. We’ll make service-api-user and the ml-ops group owners of the folder, then restrict user access to read, group user to read and write, and none to others:

sudo chown service-api-user:ml-ops keys deployed_models
sudo chmod 750 keys deployed_models

Note that 750 is the octal equivalent to u=rwx,g=rx,o= in the chmod command.

We’ll do the same for proxy-user so that only the NGINX proxy can read the SSL certificate and private key for the certificate:

sudo useradd proxy-user

Also, add the user in the docker-compose file for the NGINX proxy container:

services:
proxy:
image: your_proxy_image
user: proxy-user
...

We restrict the use of an ssl volume with the following command, where we make proxy-user and the ml-ops group owners for the folder, then restrict user access to read, group user to read and write, and none to others:

sudo chown proxy-user:ml-ops ssl
sudo chmod 750 ssl

Here, we used Linux permissions to demonstrate how to use permissions for least-privilege access control. In cloud environments such as AWS and Azure, this can be achieved by using policies that contain the platform’s syntax to ensure least privileged access.

This section completes our implementation of security controls to secure our adversarial AI playground. In the next section, we will walk through how to safeguard critical artifacts before reaching our adversarial AI playground.

As we mentioned earlier, one of the significant differences between AI and traditional systems is that AI depends on data for its development. It also introduces a new type of artifacts – that is, models – which are critical and sensitive assets. This difference brings security risks, even at development time. This section will walk you through defenses we can introduce to secure the confidentiality and integrity of our AI solution artifacts before they reach production.

Before deploying our Flask application, ensuring that the Python code has no security vulnerabilities is essential. This is known as source code analysis and it’s also used for SAST. There are many SAST tools available. You can find out more at https://owasp.org/www-community/Source_Code_Analysis_Tools.

Bandit is a popular open source SAST tool for Python that’s designed to find common security issues in Python code.

We can install Bandit using pip:

pip install bandit

Then, we can navigate to each source code directory and run the following command:

bandit -r .

Bandit will scan the Python files in the directory and report any security issues. The -r parameter makes it recursive and covers all subdirectories. Our sample ImRecS doesn’t have any significant vulnerabilities to address:

Figure 3.3 – Bandit static source code analysis summary

Figure 3.3 – Bandit static source code analysis summary

You should always review and address vulnerabilities, especially those that are high and critical. The scans should be done regularly and before deploying.

Securing dependencies with vulnerability scanning

Section titled “Securing dependencies with vulnerability scanning”

While our Python code might be secure, the libraries and the container images we use might have vulnerabilities we need to detect and remediate. This is known as component analysis or software composition analysis (SCA). You can learn more at https://owasp.org/www-community/Component_Analysis.

Trivy is a popular open source vulnerability scanner for third-party containers, libraries, and other artifacts.

You can install Trivy using the instructions at https://aquasecurity.github.io/trivy/v0.18.3/installation/.

You can use the following command to scan your project for third-party vulnerabilities:

trivy fs .

The preceding command scans the current directory and produces a report, as shown in the following screenshot:

Figure 3.4 – Trivy vulnerabilities scan summary

Figure 3.4 – Trivy vulnerabilities scan summary

Trivy relies on requirements.txt files to analyze dependencies. For ImRecS, we can see some vulnerabilities in the Pillow image library, which we can address by installing the latest version. In the requirements.txt file, we had the following:

Pillow==9.2.0

Removing the version number and installing the latest version solves the problem.

This may not always be possible. For instance, there might be no fix yet, or the dependency is introduced indirectly (transitive dependency) by another package that only works with the vulnerable version. In that case, you will need to understand the vulnerability and all other mitigations that may make it not exploitable. You can avoid including unfixed issues with --ignore-unfixed and allow-list issues you have already evaluated by using .trivyignore files containing vulnerability IDs such as CVE-2022-45199.

Similarly, before pushing your container images, scan them with Trivy:

trivy image <YOUR_IMAGE_NAME:TAG>

First, you must find the image name and tag by running the following command:

docker images

Address any vulnerabilities Trivy identifies before deploying the containers. There are some high and critical vulnerabilities, as depicted in the following screenshot:

Figure 3.5 – open-ssh critical vulnerabilities detected by Trivy

Figure 3.5 – open-ssh critical vulnerabilities detected by Trivy

The critical ones are in the open-ssh OS package. None have a fixed version (at the time of writing).

Since we don’t use SSH clients from the host, we can mitigate the critical one by removing the package in the Dockerfile by adding the following:

RUN apt-get remove -y openssh-client

Even better, you can use the slimmed-down version of the base image in your Dockerfile that does not have it installed:

FROM python:3.10-slim

Since this is a learning exercise, removing openssh-client is sufficient to demonstrate this approach.

For real-life scenarios, you would need to spend time assessing and mitigating findings rated with high severity. For instance, some are related to Perl, and we don’t use Perl. Removing all the unnecessary components would be a part of this exercise.

You may have noticed, but Trivy also reported that we store a private key in our source code folders:

Figure 3.6 – Trivy detecting a secret leak

Figure 3.6 – Trivy detecting a secret leak

Secret scanning is essential since we don’t want to leak secrets such as passwords, API tokens, or private keys via our GitHub repository, especially for production systems. This would hand over the keys of the castle to attackers. We have mitigated this vulnerability by excluding the contents of the SSL in the .gitignore file, which prevents them from being leaked to the git repository.

There are more sophisticated ways of doing secrets management. A good starting point is the OWASP Secrets Management Cheatsheet at https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html.

So far, we’ve used vulnerability scanning, which you will find in traditional application security. However, AI uses new tools, notably Jupyter Notebooks, which contain code and will have library dependencies. Because we’re using requirements.txt, the dependencies will be covered by Trivy. Sometimes, data scientists use Notebook magic commands, which are inline external commands such as the following:

!pip install <package name>

Packages that are installed directly are not included in Trivy scans. Notebooks use JSON format with Python code as code fragments in the Notebook JSON. We can apply Bandit or other static code analysis scans by exporting them to a Python file, like so:

jupyter nbconvert --to script YourNotebook.ipynb

Then, we can run Bandit. This can get messy if there are many notebooks to scan; we have written a script file to automate Bandit scanning of notebooks in a folder:

$ ./bandit-notebook-scan.sh -r notebooks -k

NBDefense is another helpful tool that’s dedicated to Notebook security. For dependencies, it uses Trivy under the hood.

We can install it using pip:

pip install nbdefense

Then, we can use it to scan all our Notebooks under the notebooks folder. NBDefense can use the open source library spaCy to detect PII information in your Notebook. Although it installs the spacy package, you will still need to download the en_core_web_trf model. You can do this with the following command:

python -m spacy download en_core_web_trf

You can scan an individual Notebook or all the Notebooks under a folder. For instance, in our case, we can scan the Notebooks we developed in Chapter 2:

nbdefense scan -r notebooks

It is reassuring to see that the CIFAR-10 CNN Notebook we used in the previous chapter has no issues:

Figure 3.7 – CIFAR-10 CNN Notebook without issues

Figure 3.7 – CIFAR-10 CNN Notebook without issues

Now, let’s learn how to secure models from malicious code.

So far, we’ve looked at securing models from physical theft or tampering. Models, especially those serialized for deployment, can be vulnerable to arbitrary code execution. This means that if an attacker can tamper with the serialized model file, they might be able to execute malicious code when the model is loaded into memory.

This is especially true for models that have been saved using Python’s pickle module, which is very popular historically. This is why we use the hierarchical data format H5 offered by Keras, but it is worth delving a bit more into the serialization risks of the Pickle format.

Note

The H5 format is Keras-specific. Safetensors offers a framework-independent alternative to pickles. For more information, see the Safetensors repository at https://github.com/huggingface/safetensors.

If a malicious actor can modify a pickled file, they can insert code that runs arbitrary commands when the file is unpickled. Consider the following scenario. Here, an attacker modifies a pickled model file to include malicious code. The unsuspecting data scientist or engineer loads this tampered model using pickle.load(). The malicious code executes automatically, potentially causing harm, stealing data, or compromising the system:

# Malicious code example:
import pickle
import os
# This is a simple representation and not an actual malicious payload.
class MaliciousPayload:
def __reduce__(self):
return (os.system, ('echo You have been compromised!',))
# Save the malicious payload
with open('malicious_model.pkl', 'wb') as file:
pickle.dump(MaliciousPayload(), file)
# Loading the tampered Model will execute the malicious command.
with open('malicious_model.pkl', 'rb') as file:
model = pickle.load(file)

Given these risks, it’s crucial to ensure that serialized models are stored securely, their integrity is maintained, and they are scanned for vulnerabilities before being loaded. Since they aren’t libraries or packages, traditional vulnerability scanners will not detect malicious code in a model file.

This is where tools such as ModelScan come into play.

ModelScan is a tool that scans serialized models, including H5 and pickles, for malicious code. We can install ModelScan with pip:

pip install modelscan

To scan our model, we can use the following command:

modelscan –p <PATH_TO_YOUR_MODEL(S)>

In our case, this will look as follows. Here, we’re scanning all models in the models folder:

modelscan -p models

Here’s a summary screen of the issues found:

Figure 3.8 – Model scan results for our model

Figure 3.8 – Model scan results for our model

As expected, our model doesn’t report any vulnerabilities.

Integrating with DevSecOps and MLOps pipelines

Section titled “Integrating with DevSecOps and MLOps pipelines”

We talked about DevSecOps and MLOps earlier in this chapter. All the security controls and deployment steps we described have been shown as manual steps. This was because we wanted to focus on concepts and techniques. We should integrate these controls and steps in our deployment pipelines for real-life scenarios. Some steps were simplified – for instance, deploying a model by copying it to a folder. MLOps can automate this as part of more sophisticated pipelines and provide a model registry and governance. We will delve into this in more detail later in this book in Chapter 15 once we’ve covered this book’s actual subject, adversarial AI.

The following section will evaluate how adequate our traditional security controls are against adversarial AI.

We have spent a lot of time securing our adversarial AI playground and our sample AI service. In this section, we will explain how the traditional security controls we have applied are very effective in protecting the environment and artifacts of AI but not the logic embedded in its brain – the ML model.

In this section, we will look at staging our first adversarial AI attack by taking advantage of AI itself to subvert how the model works and demonstrating why we need to cover it when we secure a system or conduct a security risk assessment of it.

Imagine that our ImRecS solution detects airplanes and alerts the Border Control Forces of attempted intrusions. The web application would have to become real-time, but for our security conversations, that’s not all that important. Our service is hardened, and criminals cannot break in and tamper with our model to escape detection regarding illegal airplanes crossing the border.

But a rogue data scientist claims they can use ML and math to alter a photo so that when a user sees it, they know it’s an airplane, but when our ML model processes it, it thinks it’s a bird, and the aircraft crosses the border unnoticed.

Remember our first test? We used a plane photo to test it, and it was correctly identified as an airplane:

Figure 3.9 – Original plane photo

Figure 3.9 – Original plane photo

This image is scaled to 32x32 before being processed, after which it’s classified correctly. The rogue data scientist has studied the inputs and outputs of ImRecS and has constructed a copy:

Figure 3.10 – Original airplane photo resized – correctly classified (left) and adversarial attack image misclassified (right)

Figure 3.10 – Original airplane photo resized – correctly classified (left) and adversarial attack image misclassified (right)

To the naked eye, it looks identical to the previous one, but the model classifies it as a bird!

Welcome to your first adversarial AI attack! This is called an evasion attack, and it uses perturbations (noise invisible to the naked eye) to fool the model. This perturbation is generated using a process similar to gradient descent to trick the model without tampering with it. In this case, the data scientist used the Adversarial Robustness Toolbox and a surrogate shadow model to create the perturbation:

Figure 3.11 – Creating a perturbation for an adversarial attack

Figure 3.11 – Creating a perturbation for an adversarial attack

All the criminals have to do is visually adjust the plane so that the system thinks it’s a bird. You may think this is stuff from James Bond films. However, research has shown that attacks do just that with tiny tape on road signs to confuse smart cars and accessories to evade facial recognition. You can read more about these attacks at https://www.technologyreview.com/2020/02/19/868188/hackers-can-trick-a-tesla-into-accelerating-by-50-miles-per-hour/ and https://www.theguardian.com/technology/2016/nov/03/how-funky-tortoiseshell-glasses-can-beat-facial-recognition.

In the following figure, a piece of black tape has been added to the number 3 of the speed limit sign:

Figure 3.12 – Using small black tape to fool AI in smart cars

Figure 3.12 – Using small black tape to fool AI in smart cars

This leads the AI system that’s used in a smart car to speed up instead of slowing down. We will walk through this and other evasion attacks in the following few chapters and use code to explore how they work and how to defend against them.

Traditional cybersecurity and adversarial AI

Section titled “Traditional cybersecurity and adversarial AI”

It is disconcerting that our model can be fooled despite our security hardening. But this isn’t entirely unexpected.

Traditional cybersecurity is preoccupied with protecting systems, networks, and data from digital attacks, unauthorized access, and damage. Its primary role is establishing defense mechanisms such as firewalls, intrusion detection systems, and encryption to safeguard digital assets.

Its response to threats is reactive. It relies on known threat signatures and vulnerabilities, making them less effective against novel and sophisticated attacks based on ML and how the model works.

Adversarial AI introduces a new dimension to this challenge that involves using sophisticated ML to craft malicious inputs to deceive ML models. It elevates adversarial inputs to an optimization problem that adapts based on the inputs and outputs of a model. This makes it very hard to detect using signatures.

Adversarial robustness goes beyond traditional security measures, emphasizing the importance of ensuring that AI systems can resist and recognize adversarial inputs. This helps us evolve our defense mechanisms to account for the unique vulnerabilities that AI systems present, making adversarial robustness a critical addition to the cybersecurity paradigm.

In the next few chapters, as we examine the various adversarial AI attacks, we will describe how adversarial robustness can be added to the traditional armory of signature-based detections to help us defend AI from adversarial attacks.

There has been significant research into adversarial AI, with a large number of papers backing it up.

NIST provides a detailed taxonomy of attacks in its draft paper NIST AI 100-2e2023 ipd, Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations. The paper can be found at https://csrc.nist.gov/pubs/ai/100/2/e2023/ipd.

We will use the NIST taxonomy to explore adversarial AI.

There are four types of adversarial attacks: poisoning, evasion, extraction, and inference.

Poisoning attacks involve tampering with training and validation datasets to produce malicious outcomes (backdoors) or parasitic use (Trojan horses). Evasion attacks target deployed models to facilitate fraud or misclassification and sometimes DoS attacks. They happen at different stages, but poisoning and evasion attacks target the model’s integrity.

Extraction attacks and inference attacks, on the other hand, target the model’s privacy. This could involve extracting model weights to create a similar shadow model or infer and approximate data used in the model’s training.

Finally, the seismic changes in large language models (LLMs) and adversarial AI have introduced new dimensions to Adversarial AI. Prompt injections can drive an LLM to produce unintended content or pollute the data it uses to generate its response. The ability to use LLMs to generate training data to replicate models is also an interesting development LLMs bring.

We will be covering all these in the rest of this book and, more specifically, in Chapter 12 when we talk about LLMs.

In this chapter, we covered essential security concepts and applied them in practice to our adversarial AI playground and the sample CIFAR-10 CNN AI service, ImRecS.

We took you through the journey of hardening an AI solution by strengthening the deployment environment and securing the artifacts we deploy, including the model, source code, third-party libraries, secrets, cryptographic material, and containers. We demonstrated why traditional cybersecurity is not adequate on its own to safeguard from adversarial AI attacks.

In the following chapters, we will delve into more details and practical hands-on exploration of adversarial AI and look at how the various attacks work, how to defend against adversarial AI attacks, and how to integrate these defenses in MLOps by creating MLSecOps. In the next chapter, we will start with poisoning attacks, the adversarial AI attack that attacks model training.