Skip to content
ImagineWorld

Weaponizing GANs for Deepfakes and Adversarial Attacks

node_idnode-book_adversarial-ai-defense-strategies_chapter-12-weaponizing-gans-for-deepfakes-and-adversarial-attacks
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleWeaponizing GANs for Deepfakes and Adversarial Attacks
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Weaponizing GANs for Deepfakes and Adversarial Attacks

Section titled “Chapter 12 — Weaponizing GANs for Deepfakes and Adversarial Attacks”

In the previous chapter, we built a foundational understanding of Generative AI and covered GANs in detail. Generative AI brings new challenges and GANs create a form of AI that can be used to accelerate adversarial attacks.

In this chapter, we will cover how GANs can be used in adversarial attacks. We will cover the following topics:

  • Using GANs for deepfakes and deepfake detection
  • Using GANs in cyberattacks such as evading face verification and malware detection, cracking passwords, compromising biometric authentication, cryptographic attacks, and generating payloads for traditional application attacks.
  • Using GANs in pure adversarial AI attacks to create payloads to assist other forms of adversarial AI
  • Defenses and mitigations to secure GANs, mitigate their use in adversarial attacks, and safeguard their use

Let’s start with the use of GANs for deepfakes.

Use of GANs for deepfakes and deepfake detection

Section titled “Use of GANs for deepfakes and deepfake detection”

In this section, we will explore how GANs have contributed to deepfakes and deepfake detection, starting from the basic capability of creating a fake image before moving on to how they can be used to change an existing image to a different one.

Using StyleGAN to generate convincing fake images

Section titled “Using StyleGAN to generate convincing fake images”

The evolution of NVIDIA’s StyleGAN series showcases significant advancements in GAN technology. The original StyleGAN introduced a unique architecture that provided control over image features at various scales but faced issues such as unwanted image artifacts. StyleGAN2 addressed these issues by revising the generator architecture, improving normalization, and introducing new regularization methods, leading to more realistic images and stable training.

StyleGAN2-ada further enhanced the model’s performance with adaptive discriminator augmentation. This technique dynamically adjusts the amount and type of data augmentation that’s applied during the discriminator training. Augmentations included geometric transformations, color adjustment, cropping, noise, blurring, and sharpening. This dynamic adaptation helps prevent overfitting and improves performance and stability, particularly for limited training datasets.

The latest StyleGAN3 improved temporal coherence in video generation, ensuring consistent appearance in generated objects across frames.

We will use StyleGAN2-ada to create CIFAR-10 images and demonstrate the immense value these pre-trained models bring. We’re using StyleGAN2-ada because it has a pre-trained model specifically for CIFAR-10 images.

StyleGAN2-ada comes with the following fine-tuned models that target specific datasets:

ModelDataset
metfaces.pklMetFaces 1024x1024 images of human faces extracted from works of art. See https://github.com/NVlabs/metfaces-dataset.
brecahad.pklBreCaHAD 512x512 images of breast cancer and histopathology. See https://figshare.com/articles/dataset/BreCaHAD_A_Dataset_for_Breast_Cancer_Histopathological_Annotation_and_Diagnosis/7379186.
afhqcat.pklAFHQ Cat 512x512 images of cats. This is a subset of the StarGan v2 animal faces HQ (AFH) dataset. See https://github.com/clovaai/stargan-v2/blafhqwildob/master/README.md#animal-faces-hq-dataset-afhq.
afhqdog.pklAFHQ Dog 512x512 images – the same as the one in afhqcat.pkl but for dogs.
afhqwild.pklAFHQ Wild 512x512 images – the same as afhqcat.pkl but for wildlife animals.
cifar10.pklCIFAR-10 32x32 images conditioned for a specific class.
ffhq.pklFlickr-Faces-HQ (FFHQ) dataset at 1024x1024 – see https://github.com/NVlabs/ffhq-dataset for dataset details.

Table 12.1 – Datasets to use with StyleGan-2

To use StyleGAN2-ada and generate images, we will need to download the equivalent finetuned models – that is, metfaces for faces and cifar10 for CIFAR-10 images. This can be done using the generate.py script, as follows:

python generate.py --outdir=out --trunc=1 --seeds=85,265,297,849 --network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metfaces.pkl

The script will download the pickle file – if it does not find it locally – and cache it locally, then use it to create four images for the specified seeds and store them in the –- outdir directory.

Note

Pretrained StyleGAN models are stored in pickle files. As we discussed in Chapters 3 and 5, we recommend that you download them and apply tools such as Protect.AI’s ModelScan to ensure there is no malicious code in the pickle file. For production workloads, ensure that ModelScan and integrity checks are part of retrieving the model and further model governance. For more details, see Chapter 5.

You may hit problems with running this script on your computer or cloud instance. One of the challenges with the StyleGAN series is that they compile on-the-fly discriminators and generators using NVIDIA’s GPU libraries. Consequently, they require GPUs even for inference (image generation), and they rely on old versions of NVIDIA drivers and libraries (CUDA and cuDNNs). We encountered many problems and could not get it to work on recent GPUs such as RTX4090.

Additionally, the StyleGAN series – before switching to PyTorch in StyleGAN3 – uses TensorFlow 1.x, which has not been updated since 1.15. There is also a StyleGAN3-ada PyTorch port, but it has similar issues.

Note

The most convenient way of using them to generate images is to use the NVIDIA container images, which come preconfigured with the correct drivers and libraries.

Unfortunately, the Dockerfile and documentation in StyleGAN2-ada for TensorFlow use a very old CUDA version (CUDA 10). You will struggle to make it work with more recent GPUs or cloud instances for ML. You can modify the Dockerfile so that it uses a later version of the NVIDIA container and add a couple of missing dependencies. You can create the right container by using the following Dockerfile:

ARG BASE_IMAGE=nvcr.io/nvidia/tensorflow:20.10-tf1-py3
FROM $BASE_IMAGE
RUN pip install scipy==1.3.3
RUN pip install requests==2.22.0
RUN pip install Pillow==6.2.1
RUN pip install h5py==2.9.0
RUN pip install imageio==2.9.0
RUN pip install imageio-ffmpeg==0.4.2
RUN pip install tqdm==4.49.0
RUN pip install opensimplex
RUN pip install moviepy

We’ve done this already in a forked styleGAN2-ada repository and made a few other changes. Since the NVIDIA StyleGAN2-ada repository is no longer updated, this is a safe way to get it working.

To produce new images with StyleGAN2-ada, you will need a workstation or cloud instance with an NVIDIA GPU and CUDA v11 or later. We have tested it using AWS’ ml.g4dn.xlarge in AWS SageMaker Notebook Instances for $0.8 an hour. The steps from the command line (bash, zsh, and so on) are as follows:

  1. Clone our updated repository by running the
    git clone https://github.com/PacktPublishing/Adversarial-AI---Attacks-Mitigations-and-Defense-Strategies/stylegan2-ada.git
  2. Go to the
    cd stylegan2-ada
  3. Build the
    docker build --tag stylegan2ada:latest .
  4. Run our
    ./docker-generate.sh --seeds 2-10 --model cifar10 --class 2
    This will generate images for class 2 – that is, birds. If you omit the class parameter, the script will default to 0 (airplanes). You could use the docker run command with generate.py too. However, the docker command is very long and can be tedious and error-prone. The script reduces the text to type and saves the generated images under a subfolder with a timestamp so that it doesn’t override any existing images.

To view the generated images, open the image-viewer jupyter notebook. This contains the code to view the image files of a directory as a table of images while providing us with control over parameters such as size. Let’s look at an example.

The following figure shows the higher fidelity for birds:

Figure 12.1 – StyleGAN2-ada generated CIFAR-10 bird images

Figure 12.1 – StyleGAN2-ada generated CIFAR-10 bird images

The following figure shows the higher fidelity for airplanes:

Figure 12.2 – StyleGAN2-ada generated CIFAR-10 airplane images

Figure 12.2 – StyleGAN2-ada generated CIFAR-10 airplane images

You can use the other fine-tuned models we listed earlier. Let’s create a few face images using the FFHQ dataset. The results are shown in the following figure:

Figure 12.3 – StyleGAN2-ada generated face images from the FFHQ dataset

Figure 12.3 – StyleGAN2-ada generated face images from the FFHQ dataset

Congratulations! You have created your first basic deepfakes. You can use these images for adversarial purposes or to create your defenses with data augmentation and adversarial robustness training.

These generated images are photorealistic but do not depict an existing individual.

In the next section, we’ll learn how to generate artificial images based on existing images. This is the true definition of deepfakes.

Creating simple deepfakes with GANs using existing images

Section titled “Creating simple deepfakes with GANs using existing images”

The images we created earlier are convincing but not pictures of identifiable people or objects. Deepfakes are truly effective in adversarial attacks when they mislead audiences about an existing person. We will explore two different avenues.

A relatively easy way for an attacker to create deepfakes of a person is to use StarGan v2, which specializes in image translation. An attacker could exploit the model out of the box with pre-trained models using the CelebA-HQ or AFHQ datasets. Alternatively, they can fine-tune it with other image datasets for more targeted attack scenarios.

You can apply the StarGAN v2 pre-trained model to your existing images, so long as the faces occupy most of the images. Then, you need to apply an alignment and run a sample command with a few parameters to use a pre-trained model for the CelebA dataset. You can learn more about it by going to the StarGAN v2 repository (stargan-v2) in the book’s companion GitHub repository.

Note that this is a forked repository. This is because the official repository is primarily aimed at data scientists who want to train or fine-tune the pre-trained models. Additionally, the parameters can be confusing at first. We have forked and created a simplified version of the StarGAN v2 interface for those who just want to experiment with image generation using the pre-trained models.

It is important to note that image generation relies on source and reference images. Reference images are used to transfer style to the source images. To use StarGAN v2, follow these steps:

  1. Clone the patched repository,
    git clone https://github.com/PacktPublishing/Adversarial-AI---Attacks-Mitigations-and-Defense-Strategies/stargan-v2
  2. Move to the project’s
    cd stargan-v2
  3. Run ./setup.sh. This will install the dependencies and then download the pre-trained model and the checkpoint where it was saved. It will also install the auxiliary model (Wing) that’s used for image alignment. Finally, it will set up the following structure for you, as depicted in the following figure: Figure 12.4 – Folder structure generated by the StarGAN v2 setup.sh utility

Figure 12.4 – Folder structure generated by the StarGAN v2 setup.sh utility

  1. Place your images under data/custom/raw/male and data/custom/raw/female as needed.
  2. Run the ./translate-images.sh script. This will generate a reference image called <timestamp>.jpg under data/custom/results that contains the translation result. This translation result is a matrix of the source (custom) and reference images: Figure 12.5 – StartGAN v2 results on custom images

Figure 12.5 – StartGAN v2 results on custom images

You can experiment with different translations by using other reference images. As you can see, the translation transfers certain features (hair and facial hair) from the reference image to the source images. This could be used in facial recognition or misinformation attacks.

An attacker could use their image as the reference image and the image of their target to create a version of their photo that contains their victim’s facial characteristics. Alternatively, an attacker could use the target’s image – for example, a politician – as the reference image with various source images of ill people’s faces (some of which could have been generated by another GAN or sourced from stock images). This could result in images being used to spread malicious rumors about the target’s health.

However, because of the coarse feature translation, both attacks require considerable experimentation and iterations to get a suitable variation to fool a face recognition algorithm. In the next section, we will see a more directive approach to altering image features with StyleGAN2-ada.

Making direct changes to an existing image

Section titled “Making direct changes to an existing image”

As discussed previously, GANs draw value from the latent space to create new sample images; this can be directed to influence aspects of the new image. The experimental encoder project at https://github.com/Puzer/stylegan-encoder builds on top of StyleGAN2-ada with a novel technique to project image features into latent space as numeric values and use them for translation. The project utilizes pre-trained models from the field of face alignment to extract facial landmarks from an image.

This technique is critical in facial recognition and emotion detection, with facial landmarks referring to specific points on a face, such as the corners of the eyes, the tip of the nose, the corners of the mouth, and the jawline. A list of such models can be found at https://github.com/davisking/dlib-models.

The StyleGAN encoder offers two utilities:

  • The python align_images.py raw_images/ aligned_images/ utility to extract and align faces from images
  • The python encode_images.py aligned_images/ generated_images/ latent_representations/ utility to extract facial landmarks from the aligned image and save them as latent representations in the form of saved NumPy arrays

Three feature-specific latent directions (age, gender, and smile) are also available that can be used to increase or decrease a specific feature. This allows subtle features such as smiles and altering images to be captured via GAN translation. In theory, finding the directions of any face attributes is possible. Using the smile direction and the extracted and aligned image of Donald Trump, subtle changes can be added:

Figure 12.6 – StartGAN v2 results on custom images

Figure 12.6 – StartGAN v2 results on custom images

This approach is in its early stages but creates new opportunities for attackers to produce adversarial variations of images. The following section will explore a conditional approach to directive translation.

Pix2PixHD draws from two earlier projects (CycleGAN and Pix2Pix) for image translation but adds an easier way to translate images. Like Pix2Pix, it is a conditional GAN, which means it relies on an input (for example, a label) to condition what the generated data will look like.

Pix2Pix introduced the concept of semantic labels to create photographs. Semantic labels include sketches or more coarse drawings of landscapes. The following figure shows some examples of inputs:

Figure 12.7 – Inputs for conditional image generation in Pix2Pix. Source: https://arxiv.org/pdf/1611.07004.pdf

Figure 12.7 – Inputs for conditional image generation in Pix2Pix. Source: https://arxiv.org/pdf/1611.07004.pdf

Pix2Pix inspired a community of applications. The following figure shows some of the community examples:

Figure 12.8 – Pix2Pix community applications. Source: https://arxiv.org/pdf/1611.07004.pdf

Figure 12.8 – Pix2Pix community applications. Source: https://arxiv.org/pdf/1611.07004.pdf

There was also an interesting attempt to apply Pix2Pix to the frames of a video and generate a fake one with a new person replicating the poses of the original video. You can find this at https://twitter.com/brannondorsey/status/806283494041223168.

Unfortunately, Pix2Pix does not produce high-resolution images, and the images it generates are not always photorealistic. This is where Pix2PixHD introduced a more complex architecture, enabling images to be generated with a 2048×1024 resolution. Because of its more advanced architecture, the model requires less or no fine-tuning when new semantic labels are introduced.

Setting up dependencies is always challenging for these projects, and Pix2PixHD has also released a PyPi package that can be installed via pip that installs all its dependencies.

Let’s generate some images using the semantic labels that are already in the project’s repository. To create new images, follow these steps:

  1. Clone the
    git clone https://github.com/NVIDIA/pix2pixHD
  2. Move into the projects
    cd pix2pixHD
  3. Create a new Python virtual environment and
    python -m create .venv
    source .venv/bin/activate
  4. Install the dependencies via the project’s
    pip install pix2pixhd
    This will also install all other required packages.
  5. Install the gdwon package and use it to download Pix2PixHD’s pre-trained model from their Google Drive from the command line. Then, move it to the expected checkpoints
    pip install gdown
    gdown 1h9SykUnuZul7J3Nbms2QGH1wa85nbN2-
    mv latest_net_G.pth checkpoints/label2city_1024p
  6. Run the model inference script for the
    ./scripts/test_1024p.sh

The test script will use test semantic labels of the cityscape datasets, which contain a few semantic labels for the city of Frankfurt. You can download the full Cityscapes dataset from https://www.cityscapes-dataset.com or create new ones. You can also use the semantic labels that were used in the original Pix2Pix, such as the buildings facades dataset from https://cmp.felk.cvut.cz/~tylecr1/facade/.

Once the test script has finished, you can check the results by opening the generated index.html page under pix2pixHD/results/label2city_1024p/test_latest. The page will contain all the generated images in the format shown in the following figure:

Figure 12.9 – Pix2PixHD generated images

Figure 12.9 – Pix2PixHD generated images

s

This approach creates new opportunities for defenders to create high-quality augmented datasets with synthetic images and for attackers to create deepfakes. They can be combined with video editing techniques to help produce fake videos, but there are already GANs that can generate realistic clips. The following section explores some of them.

GANs require large datasets to train or fine-tune them, which may not always be available. Few-shot adversarial learning (FSAL) introduces a meta-learning technique to overcome this challenge. Meta-learning takes advantage of the extensive work in statistics and ML to model human faces and related elements (neck, mouth cavity, and more) beyond individual instances. You can learn more about face alignment using landmarks and find a link to 230,000 3D facial landmarks at https://arxiv.org/abs/1703.07332.

The critical component of meta-learning is a CNN embedder, which uses a large corpus of videos to map frames of head images and their RGB information with facial landmarks to create embeddings. These embeddings are then used in an instance-independent manner by a model that follows the classic GAN architecture.

This allows FSAL to lean and create realistic frames of a person from very few images and, in some instances, a single one. Additionally, FSAL uses deep CNN in its discriminator to create the video clip directly rather than embed it using video editing techniques. This allows the mode to produce what researchers call puppeteering – that is, a video of a person based on another person’s moves and facial expressions.

You can find more details in the FSAL paper Few-Shot Adversarial Learning of Realistic Neural Talking Head Models, by Egor Zakharov, Aliaksandra Shysheya, Egor Burkov, and Victor Lempitsky, which was published in 2019. It can be found at https://arxiv.org/abs/1905.08233.

There is also a repository by a third party who reproduced the code provided using the paper and information from one of the researchers. This can be found in the following GitHub repository: https://github.com/vincent-thevenin/Realistic-Neural-Talking-Head-Models.

A video demo on YouTube shows the technique’s potential and limitations. The following screenshot from the YouTube video shows the implementation with a fake image emulating the expressions of the real person – that is, them winking:

Figure 12.10 – FSAL implementation demo

Figure 12.10 – FSAL implementation demo

You can watch the full video at https://www.youtube.com/watch?v=F2vms-eUrYs.

GANs represent a significant improvement in creating deepfakes with entirely new images. In the next section, we will review some other more traditional – but still effective – approaches to creating deepfakes.

So far, we have covered GAN as a new advanced application of adversarial AI to stage deepfake attacks. GANs are still evolving but can generate highly realistic images, and when combined with techniques for video generation, they can produce convincing video deepfakes. The emphasis of GANs is on convincing image generation and translation. Creating and integrating the desired results into video sequences still requires additional work.

Some popular approaches to deepfakes use technologies other than GANs to produce fake videos. Their emphasis is on making the entire workflow easier and producing good enough videos. This is a fast-evolving field of research and development, but the following are some famous examples of non-GAN deepfake technologies:

  • Face2Face: This approach, introduced in 2016, uses conventional ML to train a multilinear PCA model on pose, illumination, and expression to extract the necessary facial features and applies regression to transfer features from a source target to a target frame: Figure 12.11 – Face2Face transformations

Figure 12.11 – Face2Face transformations

No code has been released, but the details of the project can be found in the paper Face2Face: Real-time Face Capture and Reenactment of RGB Videos, by Justus Thies, Michael Zollhöfer, Marc Stamminger, Christian Theobalt, and Matthias Nießner, available at https://arxiv.org/abs/2007.14808.

A YouTube video demonstrating how effective the approach is can be found at https://www.youtube.com/watch?v=ohmajJTcpNk.

  • DeepFaceLab: DeepFace was initially introduced in 2020 and updated in 2021 by Ivan Perov et al. in DeepFaceLab: Integrated, flexible and extensible face-swapping framework. Since then, it has become widely used open source software for creating deepfakes. It claims that 95% of deepfakes are produced using its technology. Instead of GANs, DeepFaceLab uses auto-encoders deep neural networks, which generate high-quality, realistic face swaps. You can find out more about DeepFaceLab at the following links:
  • FaceSwap: Similar to DeepFaceLab, FaceSwap uses autoencoder technology and CNNs to encode facial features and swap them between images. There is no research paper, but the software is open source, and the code, along with tutorials, can be found in the project GitHub’s repository at https://github.com/deepfakes/faceswap. More detailed tutorials can be found on their website: https://faceswap.dev/.
  • First Order Motion Model: This model, introduced in a 2019 research paper, combines CNNs, RNNs, and PCA to emulate the approach that FSAL uses in its GAN settings but without GANs. It is notable for its ability to animate portraits in a photorealistic manner using just a single image. It can be used to create simple deepfake videos by animating faces based on the motion of a source video. You can find out more at https://github.com/AliaksandrSiarohin/first-order-model.
  • Diffusion models: The popular frameworks we just described have perfected face swapping, alignment techniques, and integration in video sequences. But they still suffer from some noticeable lack of photorealism. This is where GANs fit in, with their continuous improvement in output quality. The appearance of diffusion models adds a new option to image generation. Diffusion models are more stable and easier to train than GANs, making them ideal candidates for deepfakes, especially when using text-guided image generations. Here’s an example of a famous fake image created by Midjourney in 2023: Figure 12.12 – Fake image of Pope Francis generated by Midjourney

Figure 12.12 – Fake image of Pope Francis generated by Midjourney

Both GANs and diffusion models are used in experimental settings and require considerable skill. They lack the usability of DeepFaceSwap and FaceSwap. The evolution of both GANs and diffusion models and the ease of use of DeepFaceLab and FaceSwap will further revolutionize deepfakes.

We have seen some glimpses of this in research that combines the multimodal open source neural network CLIP with StyleGAN to create images based on text labels. The following figure shows the effectiveness of the research that was published in 2023 in Evading Forensic Classifiers with Attribute-Conditioned Adversarial Faces at https://arxiv.org/abs/2306.13091:

Figure 12.13 – StyleGAN image generation from text prompts

Figure 12.13 – StyleGAN image generation from text prompts

The source code for this research can be found at https://github.com/koushiksrivats/face_attribute_attack.

This text-guided generation of images is already becoming commercially available through the use of diffusion models and commercial multimodal AI solutions (OpenAI). This is a more accessible avenue for attackers to generate deceptive images.

Multimodal solutions have safety restrictions in place, but as we will see in the next chapter, as with LLMs, attackers may bypass them using prompt injections and jailbreaking. In the next few chapters, we will explore diffusion models and deepfakes as part of multimodal generative applications.

Regardless of image deepfake technology, audio deepfakes are related to increasing deepfake fidelity and challenging AI safety even more. We will review this area in the next section.

So far, we’ve focused on image and video deepfakes. Popular deepfake models either use the original audio or simple text-to-audio synthesis. However, research is also being conducted for audio in Generative AI.

Technologies such as WaveNet, Tacotron, and MelNet, developed by DeepMind, Google, and Facebook, respectively, have made significant progress in realistic voice synthesis. WaveNet uses a deep CNN architecture and is a form of generative model for audio. It produces waveforms directly. The initial Tacotron, on the other hand, was based on an advanced type of sequence-to-sequence model with attention and is primarily used for speech synthesis. With Tacotron 2, Google has combined the best of Tacotron and WaveNet into a single architecture.

You can find more information about WaveNet at https://deepmind.com/research/publications/wavenet-generative-model-raw-audio and Tacotron at https://google.github.io/tacotron/.

The Tacotron 2 paper, Natural TTS Synthesis by Conditioning WaveNet on Mel Spectrogram Predictions, can be found at https://arxiv.org/abs/1712.05884. PyTorch offers a built-in implementation for Tacotron 2 and other models (see https://pytorch.org/audio/stable/models.html), whereas there are several third-party TensorFlow models available at https://github.com/Rayhane-mamah/Tacotron-2.

Facebook’s MelNet, on the other hand, utilizes hierarchical RNNs to model and generate different time-frequency representations of audio, such as spectrograms. In 2019, researchers demonstrated its use to clone the voices of Bill Gates, Stephen Hawking, George Takei, and other TED speakers for short sentences.

You can find the generated clips at https://audio-samples.github.io/. There, you will find a variety of voices and generated music. Search for Selected Speakers to find the TED speakers clips.

The paper MelNet: A Generative Model for Audio in the Frequency Domain, by Sean Vasquez and Mike Lewis, can be found at https://arxiv.org/abs/1906.01083; note that no official code has been released. However, there are two unofficial implementations for PyTorch at https://github.com/jgarciapueyo/MelNet-SpeechGeneration and one for TensorFlow at https://github.com/YuvalBecker/MelNet.

Neither seems active and using either WaveNet or Tacotron 2 would be a better bet. In 2019, a modified version of WaveNet was used successfully to clone the voice of US actor, podcaster, and commentator Joe Rogan. There is no code, but you can find the related blog and demo at https://medium.com/@dessa_/realtalk-how-it-works-94c1afda62f0.

A more recent development is Generative AI vendors offering APIs to create lifelike spoken audio from text and sometimes a clone voice using a new generation of proprietary models. For more information see: https://platform.openai.com/docs/guides/text-to-speech and https://play.ht/voice-cloning/.

Deepfakes are a fast-evolving field that’s affecting many foundational elements of our societies and is captured in the familiar phrase seeing is believing.

In the next section, we will look at deepfake detection.

Like deepfake generation, their detection is a rapidly evolving field. In most cases, visual inspection is sufficient to detect imperfections in image artifacts or motion alignment in videos. A different way is to attempt an identity-based verification, such as by looking at key individual face landmarks to verify the claimed identity in the photograph.

Let’s walk through an identity-based detection solution to understand what’s involved.

In 2019, Facebook/Meta, Microsoft, Trust in AI, and several universities launched the Deep Fake Detection Challenge (DFDC) on Kaggle, providing a 115,000-labeled video public dataset to support the competition. There was also a private 10,000 video black-box dataset to evaluate the entries.

Interestingly, many submissions scored highly on the public dataset (82.56% accuracy) but performed poorly in the private black box dataset. In contrast, the winning entry, by Selim Seferbekov, scored 65.18% accuracy against the private black-box dataset.

The code for the winning entry can be found at https://github.com/selimsef/dfdc_deepfake_challenge. The author explains their solution on the DFDC Kaggle page: https://www.kaggle.com/competitions/deepfake-detection-challenge/discussion/145721.

The winner’s solution applies significant pre-processing. It involves doing the following:

  1. Extracting individual frames from the videos.
  2. Using the Multi-Task Cascaded CNNs (MTCNN) as part of the facenet-pytorch library to extract faces. MTCNN can extract a face as a bounding box and facial landmarks (two eyes, a nose, and two mouth corners). An alternative that other entries used, which was considered more accurate but slower and resource-demanding, is RetinaFace.
  3. Performing other basic image preprocessing, such as resizing and cropping.
  4. Using the facenet-pytorch MTCNN to extract landmarks and save them as JSON.
  5. Calculating the Structural Similarity Index Measure (SSIM) between fake and real images and using it as an input feature.

The solution applies several data augmentations to enrich the dataset, including image compression, noise, blur, resizing with different interpolations, color jittering, scaling, and rotations. This helps the model generalize better.

Finally, it trains an EfficientNet – a type of CNN autoencoder – to detect fake videos, using 32 frames for each video to calculate a prediction.

This is a heavy-processing solution and requires hours of training on multi-GPU systems. However, the solution provides a utility to download the model weights and use them for predictions in more modest NVIDIA GPU/CUDA. It also offers a Docker image file to simplify dependency management and environment configuration. You use the Docker container by following these steps:

  1. Install the NVIDIA Container Toolkit by following the instructions at https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html. The winning solution uses nvidia-docker (https://github.com/NVIDIA/nvidia-docker), but this has been deprecated in favor of the toolkit.
  2. Clone
    git clone https://github.com/selimsef/dfdc_deepfake_challenge.git
  3. Move to your
    cd dfdc_deepfake_challenge
  4. Download the weights of the
    chmod +x ./download_weights.sh
    download_weights.sh
  5. Build the Dockerfile to an image called df by running the
    docker build -t df .
  6. Run the container by running the following command, replacing DATA_ROOT with the location of a local folder where you will place your
    docker run --runtime=nvidia --ipc=host --rm --volume <DATA_ROOT>:/dataset -it df
    This will drop you into the container’s bash command-line environment. The container will have mounted your DATA_ROOT folder as /dataset. To avoid processing other videos, copy the test videos into a subfolder (for example, test_videos) under this location.
  7. Run model prediction with the
    ./predict_submission.sh /datasets/deepfake/test_videos /results.csv

This will generate a results.csv file containing video filenames and prediction labels.

The DFDC challenge is part of a significant body of research targeting deepfake image detection. Several methods have been used, including the following:

  • CNNs: These can learn to extract features from images and videos. They can be trained to classify deepfakes based on cues such as image quality, warping artifacts, or facial expressions.
  • Optical flow and CNNs: Optical flow is a technique that measures the motion of pixels between consecutive frames of a video. It can capture the temporal dynamics of facial expressions and detect inconsistencies or anomalies in deepfake videos. CNNs can be used to process the optical flow features and classify deepfake videos.
  • RNNs: These can learn to capture the temporal dependencies and patterns of facial expressions and speech and detect mismatches or dissonance in deepfake videos.
  • Transformers: These can be used to model the spatial and temporal relationships of facial expressions and speech and detect deepfakes using multi-modal and multi-scale features.
  • GANs: These can be used not only to create deepfakes but also to detect them by exploiting their fingerprints, artifacts, or inconsistencies.

Note

A complete survey of detection mechanisms with detailed references can be found in the 2023 paper Deepfakes Generation and Detection: A Short Survey, by Dr. Zahid Akhtar, at https://www.mdpi.com/2313-433X/9/1/18.

The survey concludes that despite their progress, the current efforts are not ideal, and detection methods suffer from low generalization. As a result, new deepfakes that are not exposed in the training phase evade detection.

More recently, the US Federal Trading Commission (FTC) ran its Voice Cloning Challenge, highlighting the emergence of new players in deepfake detection. For more information, see https://www.ftc.gov/news-events/news/press-releases/2024/04/ftc-announces-winners-voice-cloning-challenge.

None of these automated approaches are bulletproof, highlighting both the scale of the challenge and the need for manual inspection whenever possible. Nevertheless, these tools can be part of initial investigations for high-fidelity deepfakes. Creating ensembles of different technologies to complement each other would increase the value of these tools, depending on the implementation costs.

A defense-in-depth approach is the most sensible one, which involves combining them with human inspection and digital forensics.

This completes our discussion of deepfakes. In the next section, we will learn how GANs work in cybersecurity attack scenarios.

Using GANs in cyberattacks and offensive security

Section titled “Using GANs in cyberattacks and offensive security”

GAN and Generative AI’s ability to understand the underlying distribution and create realistic data can be harnessed for purposes other than to create deepfakes to spread misinformation. This includes helping with black-box and brute-force attacks, which inherently rely on guessing data.

Let’s start with evading face verification.

We have already discussed the ability to create composites of images of an attacker with the facial elements of the victims. This relies on face alignment and landmarks to create images that bypass popular face detection algorithms such as FaceNet and DeepFace. You can read more about these algorithms in two seminal papers:

In 2022, Sanjana Sarda from Stanford University demonstrated how to bypass face verification checks using the popular FaceNet and DeepFace algorithms and dating applications such as Bumble and Tinder. The research uses StarGAN v2, which we used earlier, to train the algorithms with a diverse and balanced dataset of attacker images and 310 images of the target user’s face. StarGAN’s seed image support allows an attacker to target a specific identity. The following figure contains screenshots of evading face verification in a dating app:

Figure 12.14 – Evading face verification with GANs in a mobile dating app. Source: https://arxiv.org/abs/2203.15068

Figure 12.14 – Evading face verification with GANs in a mobile dating app. Source: https://arxiv.org/abs/2203.15068

As we discussed earlier when exploring StarGAN, creating a successful face mapping with out-of-the-box StarGAN v2 (or other GANs, such as StyleGAN) can be challenging and it requires effort to blindly find the image with the right conditions for the mapping. Similarly, applying the directed translation (for example, lips or eyes) may not be sufficient to evade the focus of a facial detection algorithm when it comes to specific features.

Instead, the researcher used a custom implementation of FaceNet and DeepFace to generate data that drives the discriminator. An image that passes face verification is considered real. The Frobenius Norm was used as a metric to determine if images pass face verification, with a pass threshold of 0.7. This is a distance function between the target and the new image. On the other hand, Mahalanobis’ distance between a new image and all user images was used to help maximize the divergence from the user’s image without compromising identity.

These two metrics are commonly used in classification and face recognition. You can find a more in-depth explanation in the paper Facial Gesture Recognition Using Correlation And Mahalanobis Distance, which was published in 2010: https://arxiv.org/abs/1003.1819.

Some further experimentation with lighting was required to fool the dating apps, but the author also managed to achieve gender reversal by using a man’s face as the attacker to evade female photograph verification. This attack only succeeded with Bubble, not Tinder.

The details of this project can be found in the paper Face Verification Bypass at https://arxiv.org/abs/2203.15068.You can also find the source code and a demonstration Jupyter Notebook at https://github.com/Sanjana-Sarda/FVB.

Interestingly, the research points to the combination of diffusion models and GANs as future research directions.

A slightly different approach to evading biometric authentication is using GANs to generate master face images. These are images that can successfully pass authentication for a large portion of the population without any other access to user information. In 2021, EU-funded research demonstrated the use of StyleGAN to generate nine such master faces using the CASIA-Web face dataset (https://paperswithcode.com/dataset/casia-webface), which is used for face verification and identification and contains nearly half a million face images of 10,575 real identities.

The project uses a pre-trained StyleGAN model on FFHQ (face images collected from Flickr) and applies an evolutionary algorithm to generate samples that are tested against three authentication systems:

  • Based on the dlib models we discussed when we covered directed image generation with StyleGAN
  • FaceNet, which we covered earlier
  • SphereFace, an innovative CNN-based face-recognition solution

You can learn more about SphereFace in SphereFace: Deep Hypersphere Embedding for Face Recognition (https://arxiv.org/abs/1704.08063) and by reading about its official implementation (https://github.com/wy1iu/sphereface).

This research demonstrated that just nine generated images could bypass authentication successfully in 40%-60% of samples. Note that at an early stage, this is an alarming rate that could be used in dictionary attacks. There is no code sample, but you can find a detailed description of the work in Generating Master Faces for Dictionary Attacks with a Network-Assisted Latent Space Evolution at https://arxiv.org/abs/2108.01077.

DeepMasterPrints is a similar research project that generates synthetic master fingerprints and compromises the security of fingerprint recognition systems by matching many actual fingerprints. In fingerprint recognition, this is possible because fingerprint scanners only scan the part of the finger touching it, not the entire finger. Fingerprint scanners compare partial images while focusing on ridge endings and ridge bifurcations. As a result, there can be common partial images across different fingerprints that are incredibly complex to identify and generate manually, but GANs can be trained to do so at scale.

The project trained its own WGAN using NIST special database 9, which contains mated fingerprint card pairs. The dataset contains 10 fingerprints of 5,400 unique individuals.

DeepMasterPrints follows an evolutionary strategy of training the GAN and using a WGAN fitness (loss) function that counts the number of distinct identities (subjects) that were successfully matched with the generated fingerprint image. The system uses VeriFinger 9.0 SDK, a popular fingerprint authentication system, to generate data for its training process.

The fitness function also takes into account the false match rate (FMR), which is the probability of an impostor match, as a security parameter.

In addition, the system uses two more fingerprint recognition systems to test the results. These are the commercial Innovatrics IDKit 5.3 SDK and the Bozorth3 matcher algorithm, which is implemented by NIST’s Biometric Image Software (NBIS) suite (for more information on NBIS, see https://www.nist.gov/services-resources/software/nist-biometric-image-software-nbis).

The results show the exploitable potential of GANs in this area. With an FMR of 0.1%, DeepMasterPrints could spoof 23% of the subjects in the test dataset, whereas at 1%, it could spoof 77% of test subjects. To understand the implications, we need to discuss FMR.

FMR – also known as the false acceptance rate (FAR) – is essentially the frequency with which a biometric security system makes a false match, accepting an unauthorized user as a valid one. It is often used for setting thresholds regarding how close a biometric sample needs to be to a stored template to be considered a match.

Setting this threshold is a balance between usability and security. For everyday applications and consumer electronics such as smartphones or laptops, an FMR of 0.1% is an acceptable threshold (this is also the test threshold the Stanford University Face Verification research used). This would likely drop to 0.001% or even lower for high-security systems.

This means the attack would be exploitable in everyday applications, smartphones, and laptops. Despite the low percentage of 28% for this setting, because a generated fingerprint can be used for more than one identity, the attack is twice as good at spoofing a system as a random real fingerprint.

You can learn more about the project in DeepMasterPrints: Generating MasterPrints for Dictionary Attacks via Latent Variable Evolution at https://arxiv.org/abs/1705.07386.

The project’s code can be found at https://github.com/MasterMilkX/divnov-deepmasterprints.

Despite our emphasis on images and videos, GANs are as effective as other forms of data, such as text. Their unique ability to generalize a dataset distribution and produce data variances can aid offensive testers and red teams in brute-forcing attacks.

PassGAN is an example of using a GAN to improve password brute-forcing attacks. Usually, tools such as John the Ripper (JtR) and HashCat are state-of-the-art brute-forcing tools that allow attackers and red teams to crack a password by trying millions of hashes a second using combinatorial generation or dictionary attacks and replay curated datasets based on previous password data breaches (wordlists). They can also allow attackers to customize candidate passwords using rules that include concatenation or wildcards and leet speak, which involves replacing certain characters with digits or symbols – for example, p@s$wo0rd. These tools have been effective, with a success rate of over 90% against online leaked services. However, their approach requires human intuition in choosing a dictionary and creating rules, which can make this a laborious exercise.

PassGAN, on the other hand, utilizes generative adversarial training to learn the distribution of passwords from leaks from 90% of the popular password dataset RockYou with 10% of the dataset used for training. The dataset contains more than 32M passwords from various leaks, and only passwords of 10 characters or more were used for training. The model was further evaluated using the LinkedIn leak dataset, and the results were compared with JtR, HashCat, and an RNN-based password-guessing model called FLA. The results highlighted that GANs can produce good candidate passwords based on the underlying distribution and passwords that the custom rules would not have created. Let’s take a closer look:

  • PassGAN versus JtR and HashCat: PassGAN matched more passwords than any of the custom rules did. The tests included the JtR SpiderLab rules and HashCat Best64 and gen2 rules. This happened despite these rules being optimized for the datasets that were used in the evaluation process. PassGAN can produce an unlimited number of passwords, unlike custom rules, which rely on the number of rules and datasets in use.
  • PassGAN versus FLA: PassGAN and FLA had comparable performance on both testing sets, with FLA having a slight edge on the LinkedIn set. However, PassGAN does not use any prior assumptions. FLA, a recurrent neural network, relies on Markovian assumptions or probability estimation to generate passwords.
  • PassGAN and HashCat: PassGAN generated passwords that were not matched by any rule-based tool and thus could be effectively combined with HashCat to increase the number of matches. When PassGAN and HashCat Best64 were used together, they matched 51%-73% more passwords than HashCat alone.

There is a downside in the sheer volume of passwords generated by PassGAN and a contrast with the success of JtR and HashCat in cracking a high volume of passwords with smaller datasets. This highlights the value of GANs in augmenting existing password-cracking tools. A typical scenario would be running JtR and/or HashCat and, if still unsuccessful, using PassGAN to exhaust the candidate password space without resorting to pure brute force.

You can find the research behind PassGAN in PassGAN: A Deep Learning Approach for Password Guessing, by Briland Hitaj, Paolo Gasti, Giuseppe Ateniese, and Fernando Perez-Cruz, published in 2018 and updated in 2019. PassGAN’s repository can be found at https://github.com/brannondorsey/PassGAN. You can use it by doing the following:

  1. Clone our cloned version of the repository by running
    git clone https://github.com/PacktPublishing/Adversarial-AI---Attacks-Mitigations-and-Defense-Strategies/PassGAN.git
  2. Move to the
    cd PassGan
  3. Create a custom environment and
    python -m venv .venv
    source .venv/bin/activate
  4. Install the prerequisites by using the project’s requirements.txt
    pip install -r requirements.txt

You can use the PassGAN pre-trained model to create new candidate passwords or fine-tune it by training it with your dataset.

To use the pre-trained model and generate 10M new passwords in a file called mypasswords.txt, run the following code:

python sample.py \
--input-dir pretrained \
--checkpoint pre-trained/checkpoints/195000.ckpt \
--output mypasswords.txt \
--batch-size 1024 \
--num-samples 10000000

To fine-tune the model using your dataset, run the following code:

python train.py --output-dir output --training-data data/train-data.txt

In the preceding code, train-data.txt is the wordlist you want to train it on.

Finding leaked password datasets can be challenging because of the balance between preventing attacks and research. Here are some sources you can take a look at:

Figure 12.15 – Wordlists in Kali Linux

  • Find datasets online or use the new website helping password research at https://hashmob.net, which offers API access to submitted wordlists

Another research group in South Korea has proposed an optimized PassGAN that has reportedly improved PassGAN’s performance by 15%. This optimization involves replacing the GAN’s CNNs with RNNs and using a dual discriminator. CNNs are often found in the popular WGAN architectures, which focus on feature extraction, but RNNs can be better suited for text generation tasks as they can capture the sequential information and patterns of characters in passwords.

The research uses a dual discriminator by applying the D2GAN architecture (described in https://arxiv.org/abs/1709.03831), which uses two discriminators with different objectives. One discriminator tries to distinguish between real and fake passwords generated by the generator, while the other discriminator tries to distinguish between fake passwords and random noise. The generator tries to fool both discriminators by trying to produce realistic passwords.

Recurrent GANs Password Cracker For IoT Password Security Enhancement can be found at https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7309056/. It also describes using the research via TensorFlow Lite to improve IoT password security.

The authors have not produced their source code, but there is a simple third-party implementation at https://github.com/ponedo/rnnPassGAN-password-cracking that compares both the CNN and RNN-based versions.

A different application of GANs is to evade malware detection. MalGAN applies Generative AI to a GAN, where the discriminator acts as a substitute detector for malware, optimizing the creation of malware that evades detection. MalGAN is beneficial in scenarios where a malware author targets Windows API DLLs and emulates the published DLL namespace and API signature to invoke malware code from a substitute.

Since the aim is to shield malware rather than rewrite it, the GAN’s generator takes a concatenated vector of a vectorized malware sample and compares it with a random one. The generator is trained to add irrelevant features that will fool the detector rather than modify the malware samples, which may render them ineffective.

The discriminator (substitute detector) uses a black-box detector to label the generated adversarial samples and uses them for retraining. In addition to the adversarial examples, benign samples with labels are added to the training batch, and both are used to train the discriminator.

MalGAN can successfully reduce the true positive rate of various classifiers to nearly zero and quickly adapt to retrained models. ML algorithms that are used by antivirus software require large adversarial samples to retrain and adapt. In contrast, MalGAN uses the underlying probability and can learn faster than detectors.

This leads the generator to improve its creation of hidden malware that evades detection. MalGAN is described in Generating Adversarial Malware Examples for Black-Box Attacks Based on GAN, by Weiwei Hu and Ying Tan. It was published in 2017 and is available at https://arxiv.org/abs/1702.05983. Its code is available at https://github.com/yanminglai/Malware-GAN.

Malware samples can be found at https://virusshare.com. Note that malware should not be used in unrestricted environments to avoid infection and stop malware from being spread. Instead, you should use Cuckoo, an open source malware sandboxing system, as an automated and dynamic malware analysis system. For more information on Cuckoo for malware analysis, see https://cuckoo.readthedocs.io/en/2.0.7/.

Cuckoo allows you to submit malware for analysis and returns a JSON report. MalGan extracts API features that are required for training from Cuckoo reports.

MalGAN has inspired other projects, including the following:

  • An implementation of PDF malware detection. This can be found at https://github.com/lzylucy/Malware-GAN-attack.
  • An improved re-implementation that uses PyTorch and supports CUDA for 30x time faster training. It was tested with the advanced SLEIPNIR malware dataset and a simple command-line script to generate new samples. Once you’ve cloned the repository, the script can be called
    python main.py Z BATCH_SIZE NUM_EPOCHS MALWARE_SAMPLES_FILE BENIGN_SAMPLES_FILE
    Here, Z is the latent vector dimension; the rest of the parameters are self-explanatory. Both MALWARE_SAMPLES_FILE and BENIGN_SAMPLES_FILE are serialized NumPy vectors that were generated from Cuckoo reports. Here’s a quick example of using the script with the original MalGAN dataset:
    python main.py 10 32 100 data/trial_mal.npy data/trial_ben.npy
    This re-implementation is highly recommended over the source code and can be found at https://github.com/ZaydH/MalwareGAN.
  • A research paper on an improved version of MalGAN. It used multiple benign samples against one malware sample to reduce detectability in the generated samples. Unlike MalGAN, it also includes a list of all APIs instead of selecting a few based on importance. These changes reflect a typical malware scenario where attackers focus on a single malware item and experiment on variants. The Improved MalGAN: Avoiding Malware Detector by Leaning Cleanware Features paper can be found at https://ieeexplore.ieee.org/document/8669079, while the source code can be found at https://github.com/tubutubucorn/Improved_MalGAN.

Next, we’ll look at how GANs can be used in cryptography and stenography.

Like breaking passwords with PassGAN, CipherGAN was the first to attempt to break encryption ciphers and decrypt messages. CipherGAN focuses on simple shift ciphers. These originate from the first substitution cipher, Caesar’s cipher, when Julius Caesar substituted each letter with one three places further down.

The Vignere cipher is a more complex shift cipher that was designed to resist frequency analysis, which is used to break shift ciphers. A secretly exchanged key is used, and each letter of the key determines the shift position for the plain text. For instance, if we use the word CRYPTOGRAPHY as the key to encrypt Hello, H will be substituted with J because C is in position 2, E would be substituted with V because V is in position 22, and so on. This makes it harder to break it using frequency analysis but can be time-consuming and complicated if different languages and alphabets are used and mixed. In practice, these ciphers aren’t utilized, except for educational purposes.

CipherGAN uses a variation of CycleGAN, and it easily outperforms frequency analysis with a 100% score on shift ciphers and a 99.7% score on the Vignere cipher. You can read more about CipherGAN in Unsupervised Cipher Cracking Using Discrete GANs at https://arxiv.org/abs/1801.04883.

The code for this can be found at https://github.com/for-ai/CipherGAN.

Unified Cipher Generative Adversarial Network (UC-GAN) is a 2023 re-reimplementation of CipherGAN in PyTorch that uses CUDA to make it faster. It aims to use the same GAN for multi-domain architecture – that is, different ciphers – and achieves similar good results on more ciphers, albeit via shift and substitution.

You can find out more about the UC-GAN’s re-implementation in Automated Classical Cipher Emulation Attacks via Unified Unsupervised Generative Adversarial Network at https://www.mdpi.com/2410-387X/7/3/35. The source code can be found at https://github.com/tdn02007/UC-GAN-Unified-cipher-generative-adversarial-network.

The researchers plan to cover more modern block ciphers, but these are early promising steps and do not have the success and impact of PassGAN. A recent theoretical assessment on the use of GANs in breaking more advanced ciphers (for example, AES) did not produce any results and reached the same conclusion that more work is needed. You can read more in Applications of Neural Network-Based AI in Cryptography, published in 2023, at https://www.mdpi.com/2410-387X/7/3/39.

These are research efforts to watch out for but are not a threat to breaking encryption at this stage.

Steganography, on the other hand, encrypts data by embedding it into images in a way that it can’t be detected by human inspection. This is intrinsically related to images, making it a good fit for GANs to produce excellent results. There are several research papers, but only a couple have published source code.

Stegano-GAN is the most mature and offers a pre-trained model for out-of-the-box steganography. To use this GAN and encode a text message in an image, you need to follow these steps:

  1. Clone the forked repository, which contains an additional requirements.txt file. Alternatively, you can create a Stegano-GAN directory and save the content of the requirements.txt
    git clone https://github.com/PacktPublishing/Adversarial-AI---Attacks-Mitigations-and-Defense-Strategies/SteganoGAN
  2. Move to the
    cd SteganoGAN
  3. Create and activate a Python environment. This is important since Stegano-GAN relies on specific early versions of libraries (for example, PyTorch 1.0.0), and without a virtual environment, you will mess up your main Python installation. You can create and activate the environment by running the
    python -m venv .venv
    source .venv/bin/activate
  4. Install the dependencies in the requirements.txt file we have provided. Although Stegano-GAN provides a pip package to install it as a package and its dependencies, it installs the latest version of the dependencies. As a result, if you don’t run this step, the next step will install the latest versions of the dependencies, and Stegano-GAN will
    pip install -r requirements –force-reinstall
  5. Once the installation is completed, run the
    steganogan encode /path/to/source/image "My secret message"
    This will generate a new image with the encoded message.
  6. The image’s recipient can decode the message by following the same steps but running the
    steganogan decode /path/to/received/image

You can find out more about Stegano-GAN in the project’s repository at https://github.com/DAI-Lab/SteganoGAN and the published paper SteganoGAN: High Capacity Image Steganography with GANs at https://arxiv.org/abs/1901.03892.

A more advanced project, Invisible Steganography GAN (ISGAN), demonstrates using GANs to embed complex grayscale images in an invisible steganographical manner.

The ISGAN research paper Invisible Steganography via Generative Adversarial Networks, published in 2018, which can be found at https://arxiv.org/abs/1807.08571 also displays the preceding results. The implementation code can be found at https://github.com/Marcovaldong/ISGAN.

Note

Given the current progress, it is more likely that GANs will be used by adversaries in steganography rather than cryptography.

This completes our review of how GANs can be used to facilitate attacks or offensive security. In the next section, we will discuss defenses and mitigations.

Another interesting and similar application of GANs is described in Generative Adversarial Network (GAN)-Based Autonomous Penetration Testing for Web Applications, by Chowdhary et al., published in Sensors Journal in 2023.

Part of an autonomous web penetration testing framework, it uses GANs to generate attack payloads that bypass web application firewalls (WAFs) and exploit vulnerabilities such as XSS and SQL injection.

The research relies on using BurpSuite to replay payloads against intentionally vulnerable applications such as Damn Vulnerable Web App (DVWA), Gruyere, and other Open Worldwide Application Security Project (OWASP)-vulnerable applications. OWASP’s Top 10 list of security vulnerabilities has become the benchmark for application security.

Semantic tokenization handles the representation of web payloads for GAN usage. It relies on a tokenization technique from NLP called byte pair encoding (BPE), which eliminates unseen words. Semantic tokenization combined BPE with markers such as <script>, <>, HTML tags (for example, <A>) parameters (for example, href), and names (for example, JavaScript) to create a semantic representation and compress or discard unseen parts of the payload’s body.

Another related problem is that attacks may be sequences of such payloads with a mixture of malicious and benign items. The research uses conditional labeling to inform the model of the harmful items within the sequence to address this. The labeling is ok if the payload has created a vulnerability, fail if it has not, and error if an error occurred during replay. The labeling process allows security expertise to be harnessed in creating initial datasets that the generator uses to create new samples.

The discriminator of the GAN relies on payload evaluation to be generated against the vulnerable applications. The GAN is trained like a reinforcement agent, achieving a higher reward when the attack is successful and a policy gradient with statistical Monte Carlo search for when it fails.

A set of LUA scripts and the testing PhantomJS library are used to coordinate the attack replay and validation processes.

This research has been tested against Azure WAF and OWASP’s ModSecurity rules, with 8% of the generated samples bypassing WAF detection. This may sound low, but attackers only need a few successful payloads to breach a system.

The research paper can be found at https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10534908/, but unfortunately, no code has been published yet.

GANs can be used to generate payloads in adversarial AI attacks. In Chapters 8 and 9, we saw the pivotal role GANs play in generating payloads for model extraction, model inversion, and inference attacks.

In contrast, we looked at gradient-search methods for evasion inference, such as FSGM, Calling & Wagner, PGG, and others. These are still state-of-the-art attack payload generation methods, but there is ongoing research to utilize GANs to create adversarial attack samples for evasion attacks.

One of the first approaches was the Universal Adversarial Perturbation (UAP) research, which uses a GAN to find model-specific yet image-agnostic perturbations that can fool pre-trained classifiers. Their results (documented in their research paper, Universal adversarial perturbations, at https://arxiv.org/abs/1610.08401) are promising. They achieve the highest fooling ratio for the target network (around 93% for VGG-F and CaffeNet and 77.8% for VGG-19) and varying results for other architectures, with the best being VGG-19 scoring above 53% for VG-F, CaffeNet, GoogleLeNet, VGC-17, and Resnet-152. Their code can be found at https://github.com/OmidPoursaeed/Generative_Adversarial_Perturbations. You can find instructions on how to adapt it and a ready example to use against ImageNet by running the following command:

python demo_inception.py -i data/test_img.png

Generative adversarial perturbations (GAP) also extends the search for universal perturbations for targeted attacks and image-specific but model-independent payloads. It uses the difference between the target and desired outputs to drive the GAN. It reports findings similar to UAP’s accuracy, but it also reports much faster cycles compared to gradient-search methods and demonstrates the ability to generate transferable perturbations without multiple gradient computations. The code is available at https://github.com/OmidPoursaeed/Generative_Adversarial_Perturbations. It contains links to related research papers and a simple command-line Python utility to generate perturbations with the pre-trained GAN. Due to GAP’s extended scope, the utility offers far more parameters than UAP.

AdvGAN is another GAN for adversarial attacks. The project has performed well in a public black-box attack challenge, achieving 92.7% accuracy in black-box attacks using the MNIST dataset. You can find the leaderboard for this challenge at https://github.com/MadryLab/mnist_challenge. There is an unofficial implementation of AdvGAN at https://github.com/ctargon/AdvGAN-tf and a few enhanced implementations, including https://github.com/GiorgosKarantonis/Adversarial-Attacks-with-Relativistic-AdvGAN, which reports 98.12% accuracy against the public challenge secret model, and https://github.com/yegmor/Adv-GAN_Project, which achieves a 99% success rate on a simple MNIST model.

AdvGan++ is an AdvGan enhancement that uses extracted features rather than the actual images as input, and it reports better performance than GAP and AdvGAN. There is no code repository for AdvGAN++, but if you’re interested, you can find the detailed training algorithm in the 2019 research paper AdvGAN++: Harnessing latent layers for adversary generation at https://arxiv.org/abs/1908.00706.

Similarly, GAP++ is a GAP enhancement that uses conditional GANs and the sample label as the condition for targeted evasion attacks, allowing the same model to be used rather than having to train a GAN for each target. Like AdvGAN++, there is no code repository for GAP++, but the 2020 paper GAP++: Learning to generate target-conditioned adversarial examples details its design. This paper can be found at https://arxiv.org/abs/2006.05097.

More recently, the Attack-Inspired GAN (AI-GAN) uses the same conditional GAN approach to use GANs for targeted attacks, but it also introduces an attacker model in addition to the generator and discriminator models. The attacker trains the discriminator adversarially, and this seems to produce good results, with average success rates of up to 99% for MNIST and 95% for CIFAR-10. AI-GAN scales well for more complex datasets such as CIFAR-100, and once trained, it can help stage an attack in less than 0.01 seconds as opposed to 0.06 seconds for FGSM, 0.7 seconds for PGD, and more than 3 hours for the Carlini-Wagner method. You can find out more about AI-GAN in the 2021 paper AI-GAN: Attack-Inspired Generation of Adversarial Examples at https://arxiv.org/abs/2002.02196. Its unofficial implementation can be found at https://github.com/Scintillare/AIGan.

These GANs are part of evolving research, with GANs still not generally exceeding the success rates of gradient-search methods. However, unlike gradient-search methods, GANs work without the need for gradients. As a result, they can produce large volumes of adversarial samples quickly without lengthy iterative searches where several queries must be made to the model. This makes GANs less detectable, especially once trained, and they can generate several samples, making them ideal for both attacks and adversarial test sample generation.

Similarly, unlike gradient-search methods, these GANs can be used in attacks against classifiers such as random forests, not just ANNs. For the same reasons, GANs are friendlier to black-box settings, where obtaining data and calculating gradients can be challenging.

Generative AI increases our security concerns. In addition to defending GANs against adversarial attacks, we also need to think of how best we can protect against GAN-assisted adversarial attacks. Finally, Generative AI brings a new dimension to adversarial attacks with fake content and misinformation.

We will use GANs to explore how to respond to the security challenges that Generative AI brings. We will revisit these three themes in the following few chapters when we cover two other key types of Generative AI, namely LLMs and diffusion models.

In previous chapters, we covered adversarial AI threats for predictive AI. How do these apply to GANs and other forms of Generative AI?

Although GANs can facilitate evasion attacks, these attacks do not apply to GANs themselves. This is because GANs are not used for predictions or classifications. Poisoning attacks, on the other hand, can be used against GANs. An attacker, for instance, could poison GAN training data or tamper with a GAN model to achieve transitive data poisoning in a scenario where GANs are used for data augmentation. In this scenario, the GAN will indirectly produce poisoned data in augmented datasets that are used for model training.

Privacy attacks on GANs are also possible, but they occur less frequently than they do for predictive AI since they are more likely to be used for data generation and less likely to be deployed via server-side APIs or apps. As a result, they are more likely to be susceptible to white-box or supply-chain attacks. The most popular GANs are available as downloadable pickle files, increasing the supply-chain risks we highlighted in Chapter 5.

Applying the model and data protection safeguards we discussed in the previous chapters can help us defend against GANs and include model and data provenance (where does the GAN model come from? Is it an NVIDIA repository or someone’s Google drive?), access control and governance with MLOps, pickle scanning, thorough testing, and so on.

When GANs are deployed as part of a publicly available application, such as a photo repair service or mobile app, the mitigations we discussed in previous chapters apply here too. Authentication, gated APIs, access control, model protection for mobile development, API rate limiting, monitoring, auditing, and alerting are critical defenses against privacy attacks and misuse.

By applying these security measures, we can secure GANs and be aware of the different contexts.

Unlike predictive AI, GANs can be used as adversarial tools, especially in generating adversarial payloads for traditional cybersecurity attacks, as well as evasion and privacy attacks. Standard defense-in-depth security will help alleviate conventional cybersecurity attacks. The defenses against evasion and privacy that we discussed in previous chapters apply equally to GAN-assisted attacks.

However, as we saw with AI-GAN, GANs may reduce the detectability of attacks because, unlike gradient-search methods, which generate adversarial samples, they do not need to access the model once trained.

API rate limiting and monitoring will work while the attacker GAN collects data for training and evaluating the GAN, which could be circumvented by using a shadow model.

A defense here would be to use GANs to create adversarial test data and support adversarial training and robustness. There is already research on using GANs to defend against adversarial attacks, with Defense-GAN being the best-known effort in this area.

Defense-GAN is trained using unperturbed images to learn the underlying uniform data distribution. At inference time, input images are reconstructed to remove adversarial perturbations before they’re passed to the target classifier. This is described in the 2018 paper at https://openreview.net/pdf?id=BkJ3ibb0-. Its code can be found in the Defense-GAN repository at https://github.com/kabkabm/defensegan.

To use Defence-GAN, follow these steps:

  1. Clone the repository, create a virtual environment, and install all the dependencies from the project’s requirements.txt file.
  2. Download the dataset of interest – for example, mnist – and train the network by running the
    python train.py --cfg output/gans/mnist
    You can use more parameters to fine-tune training. These parameters are documented in the repository’s README file.
  3. Emulate white-box or black-box attacks to evaluate the efficacy and accuracy of the trained defense GAN. You can do this with two scripts, whitebox.py and blackbox.py. For instance, to emulate a MNIST black box attack, you can run the
    python blackbox.py --cfg output/gans/mnist \
    --results_dir defensegan \
    --bb_model targetModel \
    --sub_model substitude_model \
    --fgsm_eps 0.3 \
    --defense_type defense_gan

Defense-GAN is experimental and focuses on three datasets: MNIST, Fashion MNIST, and CelebA. You must change the code so that it fits your dataset and classifiers. Once your tests are satisfactory, you can integrate the trained GAN into your inference API.

Note

You can also use your trained Defense-GAN in your monitoring system to detect adversarial attacks.

MagNet follows a similar approach and uses auto-encoders but requires knowledge of network architecture and is less robust against Defense-GANs. You can learn more about MagNet at https://github.com/Trevillie/MagNet.

GANs can also help defend against privacy attacks by enlisting them to create realistic but anonymous training data. This is a crucial data augmentation defense; conditional GANs can help create anonymized data suitable for training.

A different approach would be to start with the sensitive data as the baseline but apply GANs or VAEs to reconstruct them in a privacy-preserving manner. DeepPrivacy is a well-known application of StyleGAN for achieving face anonymization with DeepPrivacy2 full-body anonymization. The code for DeepPrivacy2 and links to the research paper can be found at https://github.com/hukkelas/deep_privacy2.

Privacy-Preserving Representation-Learning – Variational GAN (PPRL VGAN) combines variational encodes to capture facial expressions anonymously. At the same time, the privacy-preserving adversarial protector network (PPAPNet) aims to prevent model inversion attacks from occurring on face images. You can find their source code and links to their research papers at https://github.com/yushuinanrong/PPRL-VGAN and https://github.com/tgisaturday/PPAP.

Funded by the European Union, GANs are being used in the European healthcare project EDITH to create digital twins. These are virtual representations of patients that are created using fake anonymized data. They are used for clinical research, healthcare, and education without the need to expose identifiable information about the patient. You can read more about the use of GANs in EDITH at https://link.springer.com/chapter/10.1007/978-3-030-45385-5_36.

Images have been the focus of GANs, but there is ongoing research to use GANs and anonymize text, medical records, and audio. These efforts are at an early stage and are likely to evolve, but you can find a good survey in the 2021 paper Generative Adversarial Networks: A Survey Towards Private and Secure Applications at https://arxiv.org/pdf/2106.03785.pdf.

Note

These defenses will require some investment in progressing research-level efforts to production settings and will better suit critical applications where the risk justifies the investment.

Deepfakes, malicious content, and misinformation

Section titled “Deepfakes, malicious content, and misinformation”

The ability of Generative AI to produce convincing outputs creates a profound adversarial AI challenge. As we saw, GANs and other forms of Generative AI can be abused to construct malicious content, leading to different attacks:

  • Disinformation: Deepfakes challenge the fundamental assumption of seeing is believing and can be used to spread fake news. This has been widely reported as being used in politics. The most famous example is the fake video of Ukrainian President Volodymyr Zelensky purportedly surrendering to Russia and asking the Ukrainian army to lay their arms. This was part of a coordinated attack in which attackers breached the Ukrayina 24 TV Network, amplifying the spread of the fake news. The video’s poor quality contributed to it being dismissed but did not prevent it from going viral, showcasing a coordinated large-scale deepfake attack template. https://rigorousthemes.com/blog/examples-of-deepfakes-in-politics/ provides 11 breathtaking examples of deepfake attacks in politics, including hiring London-based AI firm Synthetica to create fake TV news anchors and broadcasts: Figure 12.16 – Reported use of AI by the Venezuelan government to create fake TV news bulletins

Figure 12.16 – Reported use of AI by the Venezuelan government to create fake TV news bulletins

  • Reputational damage and extortion: In addition to misinformation attacks, deepfakes can target an individual – famous or ordinary – in unfavorable or compromising circumstances. This could be purely out of malice or to blackmail them. These attacks can be staged with traditional photo editing tools, but Generative AI makes them easier, at scale, and more convincing. This includes nudifier apps and sites that allow attackers to create fake nude photos based on existing photos. These deepfakes utilize state-of-the-art pornography Generative AI that can insert an individual into pornographic material and can be used to extort them. Unfortunately, these attacks are not always easy to address legally and can cause grave harm to an individual. You can find a good discussion in this article: https://www.huffingtonpost.co.uk/entry/deepfake-tool-nudify-women_n_6112d765e4b005ed49053822.
  • Phishing: Deepfakes can convince unsuspected consumers of fraudulent products and services, staging a compelling phishing attack. There has already been a costly phishing attack using what is believed to be a GAN-generated voice against a UK-based energy firm. The CEO of the UK firm received a voicemail from what sounded convincingly like the CEO of the Germany-based parent company requesting the urgent transfer of €220,000 to a Hungarian supplier within an hour. The UK CEO complied and transferred the money, which led to two more calls – one with the same voice claiming that the first transfer was reimbursed to the UK company and another asking for re-transmission. The lack of reimbursement and the use of an Austrian number in the third call made the UK CEO suspicious, quickly establishing the call was fake. An investigation by the firm’s insurer, Euler Hermes Group SA, led by its AI fraud expert Rüdiger Kirsch, accepted the claim, concluding that the call sounded legitimate and was generated using AI, most likely a GAN-based system. The insurer shared this information with the Wall Street Journal without revealing the identity of the victim’s company. You can read the full article at https://www.wsj.com/articles/fraudsters-use-ai-to-mimic-ceos-voice-in-unusual-cybercrime-case-11567157402.
  • Scamming: In dating or romance, fraudsters fake social media identities to create remote romantic relationships, develop trust, and convince their victims to send them money or share personal information to help the attacker defraud them. In the UK alone, the cost of dating fraud between January 1, 2019, and December 31, 2022, is reported to be a staggering £319 million. Typically, attackers use images taken from other people’s social media profiles to target vulnerable individuals, and one of the first suggested lines of defense is to use Google Image Research or TinyEye. Unfortunately, realistic photo images can help dating scammers avoid the traditional defense of image search. Furthermore, attacks can use conditional GANs or text-to-image services to create photos that appeal to the victim’s preferences, which are gathered using social media reconnaissance or chat conversations.
  • Repudiation attacks: Non-repudiation is a cornerstone of trust, and GANs can be used in adversarial attacks to challenge non-reputation. We have already seen how this can be used in face and fingerprint recognition and verification. It can be expanded to other image verification areas, including digital art, legal documents photos, digital images in legal actions, and more.

Defending against these security challenges requires a multi-pronged approach:

  • Detection: Developing robust detection techniques and tooling is an effective way to combat deepfakes. As we discussed, detection techniques vary and are still evolving. Research and evaluate the latest tools and build an ensemble of detection tools. Whenever possible, use human inspection.
  • Digital authenticity and non-repudiation defenses: Depending on the attack threat model, you may want to ensure the authenticity of images and documents that are susceptible to repudiation attacks and of high impact. This can be done using a variety of techniques:

Spoofing system-based verification, such as face and fingerprint recognition and verification, is a GAN-assisted adversarial evasion attack. Vendors should include adversarial training with GAN-generated data to help improve the robustness of solutions that rely on ML to safeguard against GAN-assisted attacks. However, this may not happen for a while or be foolproof, and users of these systems should be aware of the new attack vectors, increase thresholds, and introduce additional forms of authentication for critical systems. These are some mitigation strategies:

  • Extensive logging, monitoring, and auditing of Generative AI under your control to identify and eliminate any abuse of your Generative AI systems to produce deepfakes.
  • Ethical AI helps mitigate the risks associated with deepfakes by promoting responsible and transparent use of AI technologies. By embedding ethical guidelines and governance structures, organizations can ensure that their internal use of Generative AI adheres to moral and legal standards, thereby preventing the creation of deepfakes for unethical purposes. This includes implementing strict access controls, usage monitoring, and clear policies about the permissible applications of AI, ensuring that generative technologies are not misused to create deceptive or harmful content. Additionally, ethical AI principles encourage the development and deployment of detection systems to identify and flag deepfake content, contributing to broader efforts to combat misinformation and maintain the integrity of digital media.
  • Education and awareness to help the public learn and understand the existence and nature of deepfakes, the potential for misinformation and fraud, and the importance of verifying the source and authenticity of media they encounter. There are resources they can resort to if they suspect they are being targeted or have been defrauded by deepfake attacks.
  • Legislation plays a pivotal role in addressing the challenges posed by deepfakes. It can provide a legal framework to deter their creation and distribution for malicious purposes. By enacting laws explicitly targeting the unauthorized use of deepfake technology, governments can impose penalties for creating or disseminating deceptive or malicious content and discourage misuse. Such legislation can also mandate the implementation of verification systems by social media platforms and content distributors, ensuring that deepfakes are swiftly identified and removed. Furthermore, legal measures can protect individuals’ rights to privacy and reputation, offering recourse for victims of deepfake-related crimes and contributing to a safer digital environment.

The defenses we’ve described here are broad and may require significant investment. They must be chosen using a risk-based approach alongside threat modeling to understand the nature and impact of any potential attack on the system. We will cover this in more detail in Chapter 17 when we cover threat modelling and risk assessment.

This concludes our introduction to using Generative AI for adversarial purposes. In this chapter, we focused on GANs and how they can be used in attacks in various scenarios, from traditional cybersecurity attacks to adversarial attacks on AI and, more importantly, deepfake attacks, one of the most challenging aspects of using Generative AI technologies such as GANs.

Then, we covered defenses and mitigations and recognized the need for a multi-pronged attack based on a specific solution’s risks and threat model. We also highlighted that mitigating deepfakes requires more than particular defenses, including ethical AI guidelines, legislation, and education.

GANs are primarily used for images. The next chapter will examine the use of prompt-based attacks with adversarial inputs in text-driven interactions with LLMs.