Skip to content
ImagineWorld

Privacy Attacks – Stealing Data

node_idnode-book_adversarial-ai-defense-strategies_chapter-09-privacy-attacks-stealing-data
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titlePrivacy Attacks – Stealing Data
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 9 — Privacy Attacks – Stealing Data

Section titled “Chapter 9 — Privacy Attacks – Stealing Data”

Model inversion attacks are sophisticated adversarial AI threats targeting ML models. Their name reflects their attempt to invert the model’s prediction and reconstruct training data or sensitive information from a trained working model.

These attacks can happen in both white and black box settings:

  • White box model inversion attacks: In white box model inversion attacks, the attacker has complete access to the model, including its architecture, weights, and possibly even the training data. This level of access allows the attacker to exploit specific model details to reconstruct inputs or infer sensitive information. White box attacks can be very precise because the attacker can utilize the knowledge of the model’s internal workings to reverse engineer or deduce the data that was used during the training process.
  • Black box model inversion attacks: In black box model inversion attacks, the attacker has no direct knowledge of the model’s internals. Instead, they may only have access to the model’s input-output capabilities. That is, they can input data into the model and observe the output. Despite the lack of internal information, attackers can still attempt to infer or reconstruct private data by analyzing the outputs given different inputs. Black box attacks are more common in practical scenarios where internal details of the model are not available (e.g., APIs provided by commercial services). Black box model inversion attacks are generally more common than white box attacks. This is primarily due to the realistic nature of these attacks in real-world scenarios. Often, the internal workings of a model are hidden from the public or external entities, particularly in services where ML models are offered as APIs without exposing their internal mechanics. Thus, attackers are more likely to engage in black box attacks because they align more closely with the conditions and constraints found in many practical applications.

The approaches the model inversion attacks use vary and range from exploiting confidence scores or knowledge about the training distribution to more sophisticated techniques such as generative adversarial networks (GANs) and variational autoencoders (VAEs), which is a different type of generative neural network, typically used in compression and synthetic data generation. We will examine all these approaches in more detail.

These attacks are inference attacks and cannot extract the actual information, but attackers aim to have a good enough reconstruction that can be used to identify the original value. The exception is generative models, such as large language models (LLMs), which can memorize data that an attacker can accidentally leak or extract. This chapter focuses on model inversion as reconstruction attacks in predictive AI, such as classifiers.

Model inversion attacks pose significant risks to organizations, including data breaches, privacy violations, and potential legal and reputational damage. By exploiting these vulnerabilities, attackers can gain insights into confidential datasets, leading to intellectual property theft or compromising sensitive customer information.

The following section will describe the various model inversion types, starting with one of the first original model inversion attacks in 2015.

This section categorizes model inversion based on the technique used to reconstruct training data. We will start with the first model inversion attack in 2015 by adversarial AI researchers.

Known also as the MIFace attack because of its focus on face recognition APIs, this type of attack was one of the first to be demonstrated by a team of researchers at Carnegie-Mellon University and the University of Wisconsin–Madison, who published their work in Model Inversion Attacks that Exploit Confidence Information and Basic Countermeasures, published by Matt Fredrikson, Somesh Jha, and Thomas Ristenpart in 2015. The paper can be found at https://dl.acm.org/doi/pdf/10.1145/2810103.2813677.

This attack exploits the confidence information the model returns as a feedback signal to guide the search for the input that maximizes the confidence for a given class label. Confidence information in the classifier is the probabilities assigned to each expected call. You may recall from the previous chapter that a classifier can have either probabilistic or arg max one-hot encoded output. This type of attack targets probabilistic outputs, which contain confidence scores in the form of probabilities. In our ImRecS CIFAR-10 example, when an image is submitted, the model responds with an output that looks like this:

([[0.1, 0.05, 0.05, 0.1, 0.05, 0.1, 0.05, 0.1, 0.3, 0.1]])ffn

In our example, the model is 30% confident that the image belongs to the 9th class, 10% confident for the 1st, 4th, 6th, 8th, and 10th classes, and 5% confident for the 2nd, 3rd, 5th, and 7th classes. The class with the highest confidence is the model’s final prediction. In this case, the model would predict the 9th class.

The attack algorithm uses these probabilities in the model’s response to optimize an objective function that maximizes the likelihood of the inferred information. To achieve this, the algorithm uses gradient descent and domain-specific modifications to search the large feature space efficiently, and in summary, it follows these steps:

  1. A sample image with random pixels is fed to the classifier, which returns the prediction with confidence scores (probabilities). The response is then fed to the attacker’s system, and the following steps are repeated until the cost is below a threshold or it has reached the maximum number of iterations (attack budget). The attacker’s cost function uses the response to measure how well the model matches the name and the image quality.
  2. The cost function’s gradient is computed, showing how to change the image to improve the cost function.
  3. A processing function makes the image more realistic and natural and repeats the steps.
  4. The final image and corresponding cost value are returned.

The algorithm is implemented in the Adversarial Robustness Toolbox (ART) in the following file: https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/main/art/attacks/inference/model_inversion/mi_face.py.

You can use the implementation via the ART’s API documented in https://adversarial-robustness-toolbox.readthedocs.io/en/latest/modules/attacks/inference/model_inversion.html#module-art.attacks.inference.model_inversion.

The attack is mainly a black box attack and can be used against predictive models returning confidence scores, but the research demonstrated a white box scenario, too. Their example attacks included the following:

  • Decision trees for lifestyle surveys, inferring sensitive features such as marital infidelity or pornographic viewing habits from the survey responses and the model structure.
  • Public cloud APIs for facial recognition, where the attacker can reconstruct recognizable images of people’s faces from their names and the model confidences. They used AWS’s Mechanical Turk service to validate that the inferred images can identify an individual, although imperfectly.

Let us next look at the mitigations.

In black box settings, the attack can only occur for models that return probabilistic outputs. Some key mitigations include the following:

  • Use a Gated API pattern: The pattern isolates the API with strict network and least-privilege access security controls so that the inference API is only available to the consumer application. This prevents attackers from directly accessing your API. This may be challenging if you are using modern web applications with direct access to APIs using client-side scripts to access the inference API. Similarly, mobile applications may need to access the inference API directly. In this case, implement the pattern using an intermediate API with strong validation logic and minimization of what can be used. Strong authentication, as we demonstrated in Chapter 3 with the ImRecS web app and granular authorization, will add essential protection. These will also be key defenses if you are exposing inference APIs as commercial offerings.
  • Use the ArgMax-ed output with the target label instead of model or API output probabilities.
  • If you do need to return probabilities, use rounding or adding noise to make it harder for an attacker to stage an attack.
  • Ensure that effective model governance and least-privilege access are in place to reduce the potential for malicious internal access or leaking information to the attacker. This is especially important to prevent white box attacks.
  • Utilize privacy-preserving ML: This includes techniques such as differential privacy, which we will explore later in this chapter, and the selection of privacy-aware tree training algorithms.
  • Add noise or regularization to the model to make inversion harder.
  • Utilize API rate limiting to make it harder for attackers to run iterative optimization algorithms.
  • Use monitoring and alerting to detect attacks: As discussed in the previous chapter, traditional monitoring will benefit from visualization scripts that allow auditing and investigations to see the inputs in realistic terms (e.g., images) rather than numerical vectors.

This type of attack attempts to reconstruct data by targeting individual samples, which is hard to scale. In the next subsection, we will discuss a more generic approach.

Focusing on approximations using single sample instances makes the previous approach hard to scale for complex model architectures and large feature spaces. Since model inversion is an optimization problem of best matching a sample to the model’s output, this, for reasons similar to the discussion of functional extraction, becomes a complex equation to solve. The complexities of non-linear search space, combinatorial explosion of parameters, and expensive computation requirements are constraints that will prevent a traditional approximation scale. Additionally, using the gradient method in MIFace will not scale for deep neural networks because, without any additional constraints, this will lead to getting stuck in local minima.

A different approach is to help search the input feature space using GANs and additional knowledge distillation. We discussed using GANs in the previous chapter when talking about model extraction attacks. As a reminder, GANs apply a generative attack scenario with two models. A generator uses generative ML to create samples, and the discriminator tries to minimize the cost of sample misclassification.

Within this approach, there are variations on how knowledge distillation can help the GAN better constrain the optimization problem and generalize uncovering data distributions rather than focusing on single instances.

This was demonstrated in one of the first attempts to attack DNNs in a 2019 research paper, The Secret Revealer: Generative Model-Inversion Attacks Against Deep Neural Networks by Zhang Y, Jia R, Pei H, et al. You can find the paper at https://arxiv.org/abs/1911.07135v2/.

The key idea of this approach is to leverage partial public information, such as blurred or corrupted images, to learn distributional prior; this term is borrowed from Bayesian statistics and refers to our initial set of beliefs for a dataset whose distribution we don’t know. The approach uses this pool of public data to feed a GAN and use it to guide the inversion process. Its algorithm works in two stages:

  • Public knowledge distillation: This is where the GAN’s generator produces samples, and the discriminator guides the generator to create realistic-looking images using the public images dataset. This constrains the input space and, unlike MIFace, makes high-fidelity samples. The research also contains experiments that use auxiliary information that helps image recovery, such as reusing images published with blurring or other alterations to protect privacy.
  • Secret revelation: This is where the attacker uses the GAN to find the latent vector for a sample that will maximize the probability of the target label using the target network. A latent vector is a reduced image representation of an image capturing its essential features (e.g., color, shape, texture, etc.). The generator creates latent vectors for the pre-generated samples, and the discriminator evaluates them against the classification of the target model.

The ART and other frameworks do not offer support for Generative Model-Inversion (GMI), but you can find the researcher’s code in their GitHub repository at https://github.com/AI-secure/GMI-Attack.

GMI attacks have been demonstrated with a high success rate against three datasets, Modified National Institute of Standards and Technology (MNIST), ChestX-ray8, and CelebA, to present attack scenarios against digit classification, disease prediction, and face recognition.

In all cases, the attacker will do the following:

  1. Perform reconnaissance to understand the classifier’s input and outputs by probing the inference API.
  2. Identify publicly available images to create the initial dataset.
  3. Source any potentially related information from their target (e.g., in a face recognition scenario, blurred images posted on social media or the web).
  4. Stage the attack using the GAN to prepare the training set and infer identifiable images.

The research demonstrates that the GMI attack can achieve high success rates for recovering private images from different target networks.

Even if the public datasets lack specific identities, are untagged, are small in size, or originate from different distributions, they can still expose certain hidden characteristics of private images, including aspects such as gender, age, and hairstyle.

The following image – taken from the research paper – demonstrates the high fidelity of the results:

Figure 9.1 – Results comparison of GMI attacks

Figure 9.1 – Results comparison of GMI attacks

The authors use EMI (existing MI) to refer to the MIFace approach. The target is the original image, whereas GMI is the reconstructed image. Notice the high fidelity of the result the introduction of GANs has created. Notice also how ineffective MIFace is in a completely black box scenario without any auxiliary information.

The use of auxiliary information is particularly problematic. Given the widespread face recognition in cloud applications such as Google and Facebook, an attacker could recover a masked or blurred image’s original image as long as the target network (e.g., Google) has used that image.

The use of GANs makes the attack more effective but does not change the applicability of the defenses we discussed so far. In addition, the use of public images, including obscured ones, introduces a new risk. Differential privacy is the most effective approach for this risk, combined with raising user awareness of the risks of partially obscured images.

Note

GMI has become a benchmark in model inversion attacks, with many other attempts using it as the baseline.

Knowledge-enriched distributional model inversion (KE-DMI) attacks

Section titled “Knowledge-enriched distributional model inversion (KE-DMI) attacks”

This optimization builds on top of GMI to infer better knowledge of the target dataset and improve accuracy regarding the reconstructed image’s fidelity and similarity. It is part of research published in the Knowledge-Enriched Distributional Model Inversion Attacks paper published in 2020 by Chen S, Kahla MJia R, et al. and found at https://arxiv.org/abs/2010.04092v4.

KE-DMI is a white box attack and assumes access to the underlying model. It still uses the public data with the GAN, but unlike GMI’s generic GAN, which does not know the model, KE-DMI creates an inversion-specific GAN by adding soft labels provided by the target model. Soft labels are adjusted using a temperature adjustment of the model’s raw output or adjusting the training and testing data with label smoothing. This technique adds ambiguity, captures the uncertainty, and is used in knowledge distillation to help the student model generalize better, which is the objective of this optimization. The approach also uses the target network to generate labels for the public data and train the GAN’s discriminator to use not only the images but also the labels.

At the reconstruction phase (called distributional recovery as opposed to secret revelation in GMI), this approach attempts to model the model’s private data distribution, which it then uses to recover an image. By contrast, GMI searches for a single instance to maximize the chances of extraction.

Like GMI, the only known implementation of this attack style can be found in the research authors’ GitHub repository, which can be found at https://github.com/SCccc21/Knowledge-Enriched-DMI.

The attack has been demonstrated for similar use cases as GMI and with models available on public model hubs. Being a white box attack, the scenario would be as follows:

  1. The attacker ensures access to the target model; this may entail the following actions:
    1. They perform reconnaissance and identify the model used by the target organization. If the target uses a publicly available model, they exploit the supply chain to obtain and use a copy. This would be the easiest route to stage the attack. 2. Either a malicious insider or an attacker breaks in to steal a copy of the model for the attack.
  2. They perform the attack by collecting public data, creating the inversion-specific GAN, and staging the reconstruction.

Let us look at the mitigations.

All the mitigations discussed so far in this chapter apply here, too. However, since this is a white box attack, addressing the supply-chain implications and securing Machine Learning Operations (MLOps) are important defense aspects. This entails the following:

  • Using data augmentations and differential privacy techniques to fine-tune to avoid being a victim of a grey box hybrid attack where the baseline is used for the GAN training, whereas the inference endpoint is used for the reconstruction phase.
  • Protection of the inference point (Gated API, API rate limiting, etc.) is still relevant and a good defense in a gray box scenario.
  • Model governance and least access control to avoid white box attacks.
  • Monitoring, alerting, and auditing for both MLOps pipelines and inference endpoint.

This is similar to the GMI but attempts to increase the diversity of inferred training data rather than just the accuracy of a subset. GAN generators such as StyleGAN are used to create stylistic sample variations to achieve this.

The following figure, taken from the attacks research paper, shows how StyleGAN can be used to combine changes of two images by changing specific face features and combining them:

Figure 9.2 – Applying StyleGAN to images

Figure 9.2 – Applying StyleGAN to images

Given its similarity with the previous GMI attacks, we will not delve into any details. If you are interested to find out more about VMI, you can read Variational Model Inversion Attacks, published by Wang KFu YLi K et al. in 2022. The paper can be found at https://arxiv.org/abs/2201.10787v1, whereas the relevant code is in this GitHub repository: https://github.com/wangkua1/vmi.

This is yet another optimization on the GAN theme introducing various optimizations to improve performance and some key changes that make it very interesting:

  1. Use pretrained GAN (StyleGAN2) to create synthetic images rather than train a GAN based on curated public data. This significantly reduces the time and effort to prepare and stage the attack. While all the previous attacks train a GAN for each target architecture, and the variational ones fit one for every class, Plug and Play eliminates these steps. According to the researchers, it brings down sample generation from hours to a few minutes.
  2. By using a single pretrained GAN and transformations to match distributional shifts of different datasets and models, the approach becomes re-usable independent of the target model architecture.

This is a novel approach to the model inversion attack approach, and you can find out more in the related research paper, Plug & Play Attacks: Towards Robust and Flexible Model Inversion Attacks, published by Struppek LHintersdorf DDe Almeida Correia A et al. in 2022. The paper can be found at https://arxiv.org/abs/2201.12179v4, and the related code is at https://github.com/LukasStruppek/Plug-and-Play-Attacks.

This concludes our exploration of using GANs to assist in training data reconstruction. There are many other references, but the preceding examples capture the essential elements of modern approaches to sophisticated model inversion attacks. The attacks we cover assume a single ML learning environment. There are also model inversion attacks to distributed ML setups. Distributed model training can take place either for performance and scalability by spreading the processing or to protect privacy and confidentiality by restricting access to training data and models.

The following section will demonstrate how to stage a MIFace model inversion attack using the ART’s implementation.

This section will create a Jupyter Notebook to demonstrate a model inversion attack on a pretrained convolutional neural network (CNN) for the CIFAR-10 dataset using Keras and the ART. This example will include an initialization with an average image, similar to the approach in other ART sample notebooks:

  1. Import the libraries we will use and initialize a random seed for
    # Import necessary libraries
    import numpy as np
    import matplotlib.pyplot as plt
    from keras.models import load_model
    from keras.datasets import cifar10
    from art.attacks.inversion import ModelInversionAttack
    from art.estimators.classification import KerasClassifier
    # Set random seed for reproducibility
    np.random.seed(123)
  2. Using Keras, we load our CIFAR-10 model as usual and create an ART classifier
    # Load the pretrained CIFAR-10 model
    model = load_model(models/cifar10_model.h5')
    # Wrap the model with ART's KerasClassifier
    classifier = KerasClassifier(model=model)
  3. We use the numeric representation of images to calculate an average image. This is not a real image but an average of its RGB pixel representation. This will be useful for our model
    # Load CIFAR-10 data
    (x_train, y_train), (x_test, y_test) = cifar10.load_data()
    # Compute the average image from the training set
    average_image = np.mean(x_train, axis=0)
    # Display the average image
    plt.imshow(average_image.astype(np.uint8))
    plt.title("Average Image")
    plt.show()
  4. We can now stage the attack using the ModelInversionAttack class. The class will use our KerasClassfier wrapper and a subset of the images to evaluate using the average image as a starting point away from
    # Initialize the Model Inversion Attack with the average image
    mia = ModelInversionAttack(estimator=classifier, max_iter=1000, batch_size=1, verbose=True)
    # Select a subset of data for the attack
    x_subset = x_test[:10]
    y_subset = y_test[:10]
    # Perform the attack on the selected subset using the average image as the starting point
    x_inverted = mia.infer(x_subset, y_subset, starting_point=average_image)
  5. Once the attack has completed, we can evaluate the accuracy of the generated images with the original model and visualize the
    # Evaluate the accuracy of the inverted images
    predictions = classifier.predict(x_inverted)
    accuracy = np.mean(np.argmax(predictions, axis=1) == np.argmax(y_subset, axis=1))
    print(f"Accuracy of model on inverted images: {accuracy * 100:.2f}%")
    # Visualize some of the original and inverted images
    plt.figure(figsize=(10, 4))
    for i in range(10):
    plt.subplot(2, 10, i + 1)
    plt.imshow(x_subset[i])
    plt.title("Original")
    plt.axis('off')
    plt.subplot(2, 10, i + 11)
    plt.imshow(x_inverted[i])
    plt.title("Inverted")
    plt.axis('off')
    plt.show()

This section provided a structured approach to demonstrating a model inversion attack using a Jupyter Notebook, emphasizing the use of an average image for initialization. The code snippets are guidelines and may require adjustments based on the specific pretrained model and its preprocessing requirements.

The example completes our exploration of model inversion attacks that use adversarial AI to violate privacy and confidentiality by reconstructing data used to train the model. In our next section, we will explore attacks that deduce whether a property or an individual has been used in the training data set.

Inference attacks are privacy attacks that aim to deduce sensitive or confidential information from an ML model or its outputs without directly accessing the model’s parameters or training data. Inference attacks differ from model extraction or inversion attacks, which try to recover artifacts used in model training; by contrast, they attempt to deduce broader data, thus posing significant risks and consequences to securing privacy.

Inference attacks can be classified into two main categories:

  • Attribute or property inference attacks: These attacks aim to infer global information – such as distribution – or individual properties of the training data or the model. For example, an attacker might try to determine the average age of individuals in a dataset used to train a health prediction model or infer the architecture of a deep learning model used for image recognition.
  • Membership inference attacks: These attacks are designed to ascertain whether a particular data item was part of a model’s training dataset. For instance, an attacker could use this type of attack to determine whether a particular patient’s data was used in training a medical diagnosis model or whether a specific user’s data was included in the training set of a recommendation system.

We will examine each category, starting with attribute inference attacks.

Also known as property inference attacks, attribute inference attacks target some global or individual properties of the training data or the model, such as the data distribution, the data labels, the model architecture, or the model hyperparameters, but not about a specific individual. An adversary can launch these attacks with white box access to the model’s parameters or gradients or black box access to the model’s inference endpoint. There are different approaches involved.

The general strategy of these attacks is to train an attack model – called a meta-classifier or a meta-regressor – that the attacker uses to infer from the target model a confidential property from the observed information and determine whether the target has a specific property. The attacker can train shadow models to help develop the meta-classifier. This will typically follow this workflow:

  • Shadow model training: The attacker trains multiple shadow models to imitate the behavior of the target model using datasets with the same or similar distribution as the target model’s training data. In black box attacks, reconnaissance and exploiting the supply chain (e.g., pretrain baseline models) can help this step.
  • Generate meta-classifier training data: The attacker uses these shadow models to generate labeled inputs for the attack model. The inputs are the outputs of the shadow models, and the labels indicate whether the corresponding inputs were part of the training set.
  • Train meta-classifier: The attacker trains the meta-classifier using these labeled inputs. The training helps the meta-classifier learn to distinguish the behavior of the target model on its training members from the non-members.

The ART provides simple black box and white box implementations of this approach with different variants. The baseline implementation uses a simple neural network trained to learn the attacked feature from the rest of the features and the model’s predictions. Other traditional ML models (e.g., random forests, logistic regression) are also available as options instead of the default neural network meta-classifier. Finally, a separate white box implementation assumes access to the model and uses decision trees as the meta-classifier.

We will use the ART implementation in our example attack, but you can find the implementations under https://github.com/Trusted-AI/adversarial-robustness-toolbox/tree/main/art/attacks/inference/attribute_inference and the API documentation at https://adversarial-robustness-toolbox.readthedocs.io/en/latest/modules/attacks/inference/attribute_inference.html.

The meta-classifier approach is practical for simple classifiers but struggles with DNNs because of their complexity and the topic being an active research area. Research from Microsoft introduces a grey box attack. The meta-classifier is still used for an inference attack. Still, a poisoning attack of the model precedes the property inference attack, allowing the attacker to inject triggers that the black box inference queries use to leak information.

The threat model for this type of attack is not simply white box poisoning attacks during our model’s training but also exploiting collaborative, split learning between two partners.

The research has demonstrated promising results on the US Census Income dataset and the Enron email dataset. It was published in the Property Inference From Poisoning paper by Melissa Chase, Esha Ghosh, and Saeed Mahloujifar in 2021, and can be found at https://arxiv.org/abs/2101.11073.

The Microsoft paper does not have its code published, but a later improvement of this approach by researchers from Northeastern University, Google, and ETH Zurich. It’s called Subpopulation iNference Attack with Poisoning (SNAP) and has published its experimental code at https://github.com/johnmath/snap-sp23. SNAP is similar to Microsoft’s work but optimizes it significantly by utilizing model confidences to eliminate meta-classifier use. Instead, SNAP uses a simple test based on the distribution of model confidences. This reduces the number of shadow models (at most 4) compared to the number required in Microsoft’s research (thousands) and a low poisoning rate (less than 1% of the training dataset). This makes a simple but significantly faster attack to the stage, achieving similar or better accuracy.

Note

An exciting extension of SNAP is to estimate the exact proportion of the property of interest in the training dataset.

SNAP is described in detail in SNAP: Efficient Extraction of Private Properties with Poisoning by Chaudhari H, Abascal J, Oprea A, et al., published in 2023. It can be found at https://arxiv.org/abs/2208.12348v2.

Some of the well-known scenarios of attribute or property inference attacks are as follows:

  • Inferring the presence of a specific data point or a class in the training data, such as a genetic marker or a health condition
  • Inferring the fraction of the training data from a certain category, such as the gender or the ethnicity of the data owners
  • Inferring the environment or the setting where the model was trained, such as the location or the training time
  • Inferring the model’s architecture or hyperparameters, such as the number of layers, the activation functions, or the learning rate, to aid other adversarial attacks, such as model extraction and evasion attacks

The mitigations that we have discussed in the context of model inversion apply here too.

However, it is worth noting that differential privacy may not be an effective countermeasure against attribute inference attacks. This is because attribute inference attacks target data attributes more generally rather than individual record confidentiality. On the other hand, differential privacy aims to protect individual records. As a result, dataset-wide attributes such as aggregates may fall outside the primary scope of concerns that differential privacy is designed to protect. For example, differential privacy will help protect individual results for a particular genetic marker or health condition but may not stop the attacker from identifying the presence of such classes or aggregates.

The limitations are discussed in the Microsoft research mentioned earlier.

This is not to say differential privacy should not be applied. However, we should understand its limitations and evaluate the defenses against poisoning (data and model provenance and governance, anomaly detection, adversarial robustness, etc.) to mitigate data poisoning to leak information, aiding attribute reference attacks and white box attacks.

Gated API patterns and API rate limiting are the most effective defenses for black box attacks aiming to restrict the attack surface and make it hard for an attacker to complete their queries.

In this section, we will use the ART’s support for an inference attack to see whether we can stage an attribute attack to find out whether a sensitive feature can be detected. We will use the CIFAR-10 dataset to see whether we can accurately detect data that provide the sensitive class 0 for automobiles:

  1. Load the CIFAR-10 data and pretrained model: First, we need to load the CIFAR-10 dataset and a pretrained CNN model. You can replace pretrained_cifar10_model.h5 with the actual path to
    import tensorflow as tf
    from tensorflow.keras.datasets import cifar10
    from tensorflow.keras.models import load_model
    # Load CIFAR-10 data
    (x_train, y_train), (x_test, y_test) = cifar10.load_data()
    # Normalize pixel values to be between 0 and 1
    x_train, x_test = x_train / 255.0, x_test / 255.0
    # Load your pre-trained CNN model
    model = load_model('pretrained_cifar10_model.h5')
  2. Prepare data for the attack: Here, we prepare our dataset for the attack. The goal is to train a new model (attack model) to predict whether a sample belongs to the sensitive class based on the original model’s predictions and
    import numpy as np
    # Define the sensitive class
    sensitive_class = 0
    # Prepare labels for binary classification: 1 if the class is sensitive, 0 otherwise
    y_train_binary = (y_train == sensitive_class).astype(int)
    y_test_binary = (y_test == sensitive_class).astype(int)
    # Get predictions from the pre-trained model
    pretrained_predictions = model.predict(x_train)
    # Combine the predictions with the original features (excluding the sensitive class)
    attack_train_data = np.concatenate([x_train, pretrained_predictions], axis=1)
  3. Train the attack model: Now, we train a new model to perform the black
    from tensorflow.keras import layers, models
    # Create a simple attack model
    attack_model = models.Sequential([
    layers.Flatten(input_shape=(32, 32, 3)),
    layers.Dense(128, activation='relu'),
    layers.Dense(1, activation='sigmoid') # Binary classification
    ])
    attack_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
    # Train the attack model
    attack_model.fit(attack_train_data, y_train_binary, epochs=10, validation_split=0.2)
  4. Evaluate the attack model: Finally, we evaluate the attack model on the test data to see how well it can infer the
    # Prepare test data for the attack model
    pretrained_test_predictions = model.predict(x_test)
    attack_test_data = np.concatenate([x_test, pretrained_test_predictions], axis=1)
    # Evaluate the attack model
    attack_model.evaluate(attack_test_data, y_test_binary)

This code outlines a basic black box attack against a CIFAR-10 pretrained CNN model. Depending on your specific requirements and the sophistication of the attack model, you might need to adjust the model architecture, training parameters, or data preprocessing steps.

This completes our exploration of attribute inference attacks, which aim to infer global information about the model or its training data. In the next section, we will explore different inference attacks that, unlike attribute inference attacks, target individual data points.

In membership inference attacks the attackers try to ascertain whether a data item is part of a model’s training dataset or whether it is a black box attack and the attackers infer the membership by analyzing the model’s outputs for the specific data item. By targeting individual records, these attacks can reveal sensitive information about the individuals whose data was used for training, such as their health status, preferences, or behavior. This can lead to violating the privacy regulations and policies of the data or ML service providers.

An adversary can perform the attacks with black box access to the model’s predictions or white box access to the model’s parameters or gradients. The general strategy of these attacks is to exploit the overfitting or memorization behavior of the model, which causes the model to perform better on the training data than on the unseen data. For example, an attacker can use the model’s confidence scores or gradients to distinguish the training data from the non-training data. There are different approaches to membership inference attacks.

Shadow model attacks are similar to the use of shadow models we saw in the meta-classifier approach of attribute inference attacks. In this approach, the attacker does the following:

  • They train multiple shadow models on synthetic datasets that mimic the target model’s training data, then use the shadow models’ outputs to train an attack model that predicts the membership status of a given input. In black box settings, the attacker uses statistics to approximate the data distribution. Reconnaissance can help assemble noisy samples of the training dataset or other details that can help the heuristics of approximating the data distribution (e.g., a ResNet base model).
  • Like in other privacy attack types, shadow models exploit information leaked from confidence levels in the output of the target model. The training of the shadow models relies on continuously evaluating samples that increase the confidence with which the target model classifies. The results of these models are evaluated, and they generate a labeled dataset for the attack.
  • They use the training labeled dataset to train attack models – usually a binary classifier, one for each target model output.
  • They evaluate outputs from the target model and decide whether they belong to the training set by feeding them to the relevant attack model.

The attack described has been used with relatively good results using hospital attendance records, MNIST, and CIFAR-10 against trained models and Google and Amazon Prediction APIs. It’s described in detail in the 2017 paper, Membership Inference Attacks Against Machine Learning Models, by R. Shokri, M. Stronati, C. Song, and V. Shmatikov. It can be found at https://arxiv.org/abs/1610.05820.

This approach simplifies the shadow model approach by eliminating the training of shadow models. Instead, it uses a reference dataset to generate queries against the target model and statistical evaluation of confidence thresholds from the target model outputs. Significant confidence scores indicate membership. A linear classifier can also be trained as the attack model to help stage the attack.

This is still a black box attack, and research demonstrates it to be as effective as the shadow model approach when memorization and overfitting are relatively high. The technique is described in a couple of research papers:

  • Privacy Risk in Machine Learning: Analyzing the Connection to Overfitting by Samuel Yeom, Irene Giacomelli, Matt Fredrikson, and Somesh Jha in 2018, and available at https://arxiv.org/abs/1709.01604
  • Privacy Risks of Securing Machine Learning Models against Adversarial Examples by Liwei Song, Reza Shokri, and Prateek Mittal in 2019, and available at https://arxiv.org/abs/1610.05820

The latter publishes its source code at https://github.com/inspire-group/privacy-vs-robustness and demonstrates a concerning correlation between adversarial training and membership inference attacks.

Note

Adversarial training for evasion and other attacks increases the likelihood of membership inference attacks compared to the ones before adversarial training. This highlights the need to increase privacy-preserving techniques when applying adversarial training.

This attack assumes that the attacker only has access to the predicted labels of the target model, not the confidence scores. The attack uses a meta-classifier trained on the outputs of multiple models with different architectures, hyperparameters, and distributions; it then applies it to the target model’s output to infer the membership status of a given input. The attack has produced good results against cloud ML prediction APIs using the CIFAR-10 dataset in research settings and is ideal for black box settings. It is described in the ML-Leaks: Model and Data Independent Membership Inference Attacks and Defenses on Machine Learning Models paper published in 2018 by Ahmed Salem, Yang Zhang, Mathias Humbert, Pascal Berrang, Mario Fritz, and Michael Backes. The paper can be found at https://arxiv.org/abs/1806.01246, and the source code of their experiments can be found at https://github.com/AhmedSalem2/ML-Leaks.

A similar label-only approach is followed by other papers, which can be found at https://arxiv.org/abs/2007.14321 and https://arxiv.org/abs/2007.15528.

These types of attacks use labels only and differential comparisons to eliminate the need to create shadow models. The attack relies on the fact that an attacker can obtain some labels by probing the model, which are most likely non-members (i.e., they were not part of the training dataset). The attackers create a non-members dataset using these labels or data from another domain. They also produce a target dataset that could be members. They query the target with both datasets to obtain output probabilities.

The attacker uses a projection function to increase variance to get a diverse dataset, minimize the correlation between features, reduce redundancy and noise, and preserve the distance between the original and projected space.

The differential compassion measures the increase or decrease of distance; if the distance is decreased, the sample is considered a member.

The algorithm continues the projections until convergence. It eliminates the need for shadow models or ground truth labels. It is effective compared to all other attacks, bypassing adversarial regularization and differential privacy defenses.

The attack is described in the 2021 research paper, Practical Blind Membership Inference Attack via Differential Comparisons, by Hui, Yang, Yuan, Burlina, Gong, and Cao. The paper can be found at https://arxiv.org/abs/2101.01341, and the source code of the experiments is in this GitHub repository: https://github.com/hyhmia/BlindMI.

This involves exploiting the footprint of gradients in the Stochastic Gradient Descent (SGD) algorithm as well as the model’s parameters and intermediate computations. The attacker uses a deep learning attack model that takes as input the features extracted from the target model, such as the gradients of the loss function, the outputs of the hidden layers, the model output, the true label, and the loss value. The attack model computes a membership probability or an embedding for each data point and uses clustering or supervised learning to distinguish members from non-members.

The attack is effective in various scenarios, including the following:

  • Having access to the model after training in a classic stand-alone model development. Through insecure deployment, inadequate access control, or lax model sharing and distribution with researchers, other teams can let the attacker access gradients and other model parameters after its training.
  • Transfer learning and fine-tuning.
  • Collaborative learning that provides access to other model’s gradients.

The attack is described in the 2020 research paper, Comprehensive Privacy Analysis of Deep Learning: Passive and Active White-box Inference Attacks against Centralized and Federated Learning, by Milad Nasr, Reza Shokri, and Amir Houmansadr. It can be found at https://arxiv.org/abs/1812.00910.

The ART implements support for the black box shadow model and label-only membership inference attacks in different scenarios. Details can be found in the ART’s documentation (https://adversarial-robustness-toolbox.readthedocs.io/en/latest/modules/attacks/inference/membership_inference.html) and source code (https://github.com/Trusted-AI/adversarial-robustness-toolbox/tree/main/art/attacks/inference/membership_inference).

The membership inference attacks we have seen can occur in various attack scenarios:

  • Inferring the membership of a data point in the training data of an ML service, such as a face recognition or a sentiment analysis service. This has been the focus of most research against cloud-provided ML-as-a-service prediction APIs.
  • Inferring the membership of a data point in the training data of a collaborative learning system. This can be inadvertently a white box scenario if the attacker is part of the collaborative learning setup.
  • Exploiting online training, where the training is continuously updated with the inference data. This could prove that a user has used the AI system and a range for further inference from the system’s background (e.g., a specialized medical diagnostic center, an abortion clinic, a military assessment system, etc.).
  • These attacks can pose legal and ethical challenges for the model providers, as they may have to ensure the data owners’ privacy and security when offering or participating in the model’s service or system.

Most of the research highlights the role of overfitting and memorization as pivotal contributors to membership inference attacks. Preventing overfitting and memorization becomes a critical line of defense. Mitigations to help prevent overfitting and memorization include the following:

  • Regularization: This involves applying techniques such as early stopping, weight decay, or dropout to prevent the model from overfitting to the training data. This reduces the model’s generalization error, which is closely related to the membership advantage. In addition to the standard regularization methods, research with experimental code demonstrates adversarial regularization targeting membership attacks. The code can be found at https://github.com/NNToan-apcs/python-DP-DL. Another experimental regularization defense is based on the maximum mean discrepancy (MMD) between the softmax output distributions of the training and validation sets. This defense aims to reduce the generalization and label confidence gaps between members and non-members. The experimental code can be found at https://github.com/colaalex111/MMD-mixup-Defense.
  • Data augmentation: This involves increasing the size and diversity of the training data by adding synthetic or transformed data points. This reduces the likelihood of re-sampling an individual from the training set into the general population and improves the model’s generalization.
  • Model stacking: This uses a classical ensemble method to counteract membership inference attacks. The strategy involves a target classifier structured as a two-level tree with three distinct classifiers. The initial classifiers at the base use original data samples, and the top classifier processes their outputs. Training these classifiers on separate datasets minimizes the likelihood of the target classifier memorizing specific samples, thereby preventing overfitting.
  • Data minimization and anonymization: These are used to reduce the exposure of sensitive data to model memorization.

However, these attacks are still possible even for well-generalized models, especially in grey-and-white box settings, and therefore, solid privacy-preserving measures are an additional line of defense. Countermeasures include the following:

  • Differential privacy: This involves adding noise to the model output or the training algorithm to reduce the attacker’s membership inference opportunities. We will discuss differential privacy in more detail in the next chapter, Privacy-Preserving AI.
  • Membership inference adversarial training: This trains the model to minimize the loss on both the original objective and the membership inference objective. This forces the model to learn features useful for the original task but not for the membership inference task.
  • MemGuard: This is a defensive technique that introduces strategically generated noise into the confidence score vectors produced by the target classifier for any queried data sample. This noise is intended to confuse the attacker’s classifier, causing it to make random guesses about membership status, while still maintaining the usefulness of the confidence score vectors. The result of the research and its implementation can be found at https://github.com/jjy1994/MemGuard. Note that MemGuard is experimental, and you will need to adapt it to your own needs.

Finally, probing and querying the target model is part of all black box attacks. Securing the inference endpoint is another part of our multi-layered defense-in-depth approach. This includes defenses we discussed in previous attacks in this chapter, including gated APIs, API-rate limiting, monitoring and alerting with monitoring controls on repetitive queries, etc.

In the next subsection, we will see a practical example of using the ART to demonstrate a membership inference attack against our CIFAR-10 CNN network using shadow models.

Example membership inference attack using the ART

Section titled “Example membership inference attack using the ART”

In this example, we will use the ART, which trains shadow models to generate a meta-dataset for membership inference and conducting the attack:

  1. Load CIFAR-10 data: We’ll load the CIFAR-10 data and split it for training the target and
    import tensorflow as tf
    from tensorflow.keras.datasets import cifar10
    # Load CIFAR-10 data
    (x_train, y_train), (x_test, y_test) = cifar10.load_data()
    # Split the data for target and shadow models
    # Assuming 25% for target model and 75% for shadow models
    x_target = x_train[:12500]
    y_target = y_train[:12500]
    x_shadow = x_train[12500:]
    y_shadow = y_train[12500:]
    # Further split target data for training and testing
    target_train_size = len(x_target) // 2
    x_target_train = x_target[:target_train_size]
    y_target_train = y_target[:target_train_size]
    x_target_test = x_target[target_train_size:]
    y_target_test = y_target[target_train_size:]
    # Normalize pixel values to be between 0 and 1
    x_target_train, x_target_test, x_shadow = x_target_train / 255.0, x_target_test / 255.0, x_shadow / 255.0
  2. Load the pretrained target model using the Keras library,
    # Load your pre-trained CNN model
    model = tf.keras.models.load_model('models/cifar10_model.h5')
  3. Train shadow models: We will train multiple shadow models to simulate the behavior of the target model. The first part of the code generates a baseline shadow model using the
    from sklearn.model_selection import train_test_split
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense, Conv2D, Flatten, MaxPooling2D, Dropout
    def create_shadow_model():
    shadow_model = Sequential([
    Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
    MaxPooling2D(2, 2),
    Conv2D(64, (3, 3), activation='relu'),
    MaxPooling2D(2, 2),
    Flatten(),
    Dense(64, activation='relu'),
    Dense(10, activation='softmax')
    ])
    shadow_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    return shadow_model
    We will now use a loop to create an array of three shadow models. These models generate the training data for the membership inference attack:
    # Train shadow models
    num_shadow_models = 3
    shadow_models = []
    for _ in range(num_shadow_models):
    shadow_model = create_shadow_model()
    x_shadow_train, x_shadow_test, y_shadow_train, y_shadow_test = train_test_split(x_shadow, y_shadow, test_size=0.5)
    shadow_model.fit(x_shadow_train, y_shadow_train, epochs=5)
    shadow_models.append(shadow_model)
  4. Conduct the attack: We can now use the shadow models to train the attack model for
    # Assuming the use of ART (Adversarial Robustness Toolbox)
    from art.attacks.inference.membership_inference import ShadowModels, MembershipInferenceBlackBox
    # Prepare the shadow dataset
    shadow_dataset = ShadowModels(model, num_shadow_models=num_shadow_models)
    (member_x, member_y, member_predictions), (nonmember_x, nonmember_y, nonmember_predictions) = shadow_dataset.generate_shadow_dataset(x_shadow, y_shadow)
    # Train the black-box membership inference attack
    attack = MembershipInferenceBlackBox(model, attack_model_type="nn")
    attack.fit(member_x, member_y, nonmember_x, nonmember_y, member_predictions, nonmember_predictions)
    # Evaluate the attack
    member_infer = attack.infer(x_target_train, y_target_train)
    nonmember_infer = attack.infer(x_target_test, y_target_test)

This concludes our discussion of inference attacks.

In this chapter, we covered privacy attacks aiming to steal data by means of reconstructing training data with model inversion attacks or inferring global or instance data with attribute and membership inference attacks.

We discussed several mitigations. An underlying theme of these defenses has been the need to prevent data privacy. The following chapter will explore in detail the field of privacy-preserving AI, which includes a variety of techniques that help us minimize sensitive data exposure and protect privacy from the ground up.