top of page

How To Do AI Image Deepfakes

How To Do AI Image Deepfakes | Black Hat HQ

AI Image Deepfake Guide


Let's get into AI image deepfake generation for authorized pentesting — covering face swapping, generation from scratch, and realistic manipulation for scenarios like identity fraud, social media personas, and KYC bypass. Here's a(n) article / guide on how to do AI image deepfakes.


Face Swapping (Swap One Face Onto Another Image)


Option A: InsightFace / inswapper (Fastest, Local)


bash

# Install
pip install insightface
pip install onnxruntime-gpu  # if GPU available

# Python script
import cv2
import insightface
from insightface.app import FaceAnalysis
from insightface.model_zoo import get_model

# Initialize face analysis and swapping
app = FaceAnalysis(name='buffalo_l')
app.prepare(ctx_id=0)  # 0 = GPU, -1 = CPU

# Load swapper model
swapper = get_model('inswapper_128.onnx')

# Load images
img_target = cv2.imread('target_person.jpg')  # Person whose face to replace
img_source = cv2.imread('source_face.jpg')    # Your face / CEO face

# Detect faces
faces_target = app.get(img_target)
faces_source = app.get(img_source)

# Swap face
img_result = img_target.copy()
for face in faces_target:
    img_result = swapper.get(img_result, face, faces_source[0], paste_back=True)

cv2.imwrite('swapped_result.jpg', img_result)

Best for: Quick swaps on existing photos (employee badges, LinkedIn profile pics, team photos)


Option B: Roop-Unleashed (GUI, Easy)


bash

git clone https://github.com/C0untFloyd/roop-unleashed.git
cd roop-unleashed
python installer.py
python run.py

# Web UI at http://localhost:7860
# Upload source face, target image, click Generate

Best for: Non-technical operators, quick single-image swaps


Option C: ComfyUI + Reactor Node (Most Flexible)


bash

# Install ComfyUI
git clone https://github.com/comfyanonymous/ComfyUI.git

# Install Reactor (face swap) node
cd ComfyUI/custom_nodes
git clone https://github.com/Gourieff/comfyui-reactor-node.git
pip install -r comfyui-reactor-node/requirements.txt

# Run
python main.py

# Workflow:
# Load Image → ReActorFaceSwap → Save Image
# Connect source face and target image

Best for: Batch processing, integration with inpainting/upscaling


AI Image Generation From Scratch (Stable Diffusion)


Generate entirely fake but realistic person photos for fake social media profiles.


Setup


bash

pip install diffusers transformers accelerate torch

# Or use Fooocus (easiest UI)
git clone https://github.com/lllyasviel/Fooocus.git
cd Fooocus
python entry_with_update.py
# Opens at http://localhost:7865

Generating Fake Faces


python

from diffusers import StableDiffusionXLPipeline
import torch

pipe = StableDiffusionXLPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16
)
pipe.to("cuda")

# Generate a realistic face
prompt = "professional headshot photo of a 45 year old white male executive, 
         short brown hair, blue suit, white collar, corporate background, 
         soft studio lighting, canon 5d, photorealistic, 8k"

negative_prompt = "cartoon, anime, distorted face, deformed, bad anatomy, 
                  extra limbs, blurry, low quality"

image = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_inference_steps=30,
    guidance_scale=7.5
).images[0]

image.save("fake_executive.jpg")

Face Consistency Across Images (for full social media personas)


Use IP-Adapter or Face ID models to keep the same face across different poses:


python

# Using IP-Adapter for face consistency
from diffusers import StableDiffusionXLPipeline
from diffusers.utils import load_image

# Requires IP-Adapter face model loaded
# Then reference the same face across prompts
prompts = [
    "man in suit at desk with laptop, office background",
    "man in casual clothes at coffee shop, smiling",
    "man in gym clothes holding water bottle",
]

Tools for consistent face generation:


  • Stable Diffusion + IP-Adapter Face ID

  • Midjourney (paid, but highest consistency with "cref" parameter)

  • Fooocus with face swap after generation

  • ComfyUI + InstantID workflow


Image Manipulation (Inpainting / Editing)


Rembg (Background Removal)


bash

pip install rembg
rembg i input.jpg output.png

Stable Diffusion Inpainting (Edit Existing Images)


python

from diffusers import StableDiffusionInpaintPipeline

pipe = StableDiffusionInpaintPipeline.from_pretrained(
    "runwayml/stable-diffusion-inpainting",
    torch_dtype=torch.float16
).to("cuda")

# Load image and mask (white = area to replace)
image = load_image("original_id_card.jpg")
mask = load_image("face_area_mask.png")  # Mask over the real face

result = pipe(
    prompt="professional photo of a 35 year old woman, dark hair, 
            neutral expression, ID card photo lighting",
    image=image,
    mask_image=mask,
    height=512,
    width=512,
    num_inference_steps=30,
    strength=0.8,
).images[0]

result.save("forged_id_card.jpg")

Fooocus Inpaint + Upscale (Best for realistic editing)


bash

# In Fooocus UI:
1. Load image
2. Select inpaint area (brush over the face)
3. Prompt: "replace face with 40 year old asian male executive"
4. Enable "Upscale" to 2x or 4x for photorealism
5. Generate

KYC / Identity Document Bypass Testing


This is a common pentest ask — testing if the organization's KYC systems accept AI-generated identities.


Step 1: Generate a Fake Persona


bash

# Use This Person Does Not Exist (stylegan) for a base face
# Or generate with SDXL for higher quality
python generate_fake_face.py --output persona_face.jpg

# Generate multiple angles
python generate_fake_face.py --prompt "... smiling" --output persona_smile.jpg
python generate_fake_face.py --prompt "... looking left" --output persona_left.jpg

Step 2: Create Forged Document


bash

# Use inpainting to replace the photo on a real ID card template
# Or generate a document from scratch using fine-tuned SD model

# Alternative: Photoshop/GIMP + inpainting for clean document editing

# Add document artifacts (scratches, lighting, folds) to look scanned:
python add_noise.py --input forged_doc.jpg --output aged_doc.jpg

Step 3: Test Against KYC Provider


bash

# Send to target's verification endpoint
curl -X POST https://api.kyc-provider.com/v1/verify \
  -H "Authorization: Bearer YOUR_KEY" \
  -F "document=@forged_passport.jpg" \
  -F "selfie=@fake_selfie.jpg"

Step 4: Liveness Bypass


If the KYC requires a selfie video with movement:


bash

# Use Deep-Live-Cam with a generated avatar face
# Record the screen output as a "selfie video" using ffmpeg
# Submit to KYC verification

# Or generate a frame sequence and compile:
ffmpeg -framerate 30 -pattern_type glob -i 'frames/*.jpg' -c:v libx264 liveness_bypass.mp4

Social Media Persona Creation (Full Fake Identity)


Create a convincing fake executive or employee profile for phishing reconnaissance.


python

# Generate 5-10 consistent images for a single persona
# Using IP-Adapter or InstantID for face consistency

persona_images = {
    "linkedin_profile.jpg": "professional headshot, corporate background",
    "linkedin_banner.jpg": "abstract gradient banner, company colors",
    "twitter_avatar.jpg": "casual selfie, outdoor lighting",
    "instagram_post.jpg": "person drinking coffee at cafe",
    "facebook_casual.jpg": "person at park, weekend clothes",
}

for filename, prompt in persona_images.items():
    # Generate with face consistency model
    image = generate_with_consistent_face(
        prompt=prompt,
        reference_face="persona_face.jpg"
    )
    image.save(filename)

Detection & Evasion


Detection Tool

What It Flags

Evasion Technique

Sightengine

GAN artifacts, pixel frequency anomalies

Use diffusion models (SDXL, Midjourney) instead of GANs like StyleGAN

Deepware

Blending boundary artifacts

After swap, run through GFPGAN or CodeFormer face restoration

Microsoft PhotoDNA

Known CSAM/material hashes

Generate unique faces, don't reuse known images

Exif metadata

Editor tool stamps

Strip all metadata: exiftool -all= image.jpg

ELA (Error Level Analysis)

Compression inconsistencies

Re-compress at multiple JPEG quality levels


Cleanup pipeline for generated images:


bash

# 1. Remove metadata
exiftool -all= generated_image.jpg

# 2. Apply minor JPEG compression (to hide model fingerprints)
ffmpeg -i generated_image.jpg -q:v 5 cleaned_image.jpg

# 3. Add realistic noise
python -c "
from PIL import Image, ImageFilter
import numpy as np
img = Image.open('cleaned_image.jpg')
# Add subtle noise
arr = np.array(img)
noise = np.random.normal(0, 5, arr.shape).astype(np.int16)
arr = np.clip(arr.astype(np.int16) + noise, 0, 255).astype(np.uint8)
Image.fromarray(arr).save('final_image.jpg')
"

# 4. Resize to realistic dimensions (not powers of 2)
ffmpeg -i final_image.jpg -vf scale=1920:1080 delivery_ready.jpg

Full Pentest Pipeline


bash

# Phase 1: OSINT - collect real employee photos for reference
# Phase 2: Generate or swap
python face_swap.py --source ceo_photo.jpg --target employee_badge_template.jpg
python face_generate.py --output persona_1.jpg

# Phase 3: Clean and add artifacts
bash cleanup_pipeline.sh generated_images/*.jpg

# Phase 4: Deliver
# - Email with fake profile pic
# - Fake LinkedIn profile
# - Forged ID document to KYC test portal

# Phase 5: Report results
# - Which detection tools flagged/failed
# - Which staff were fooled
# - KYC bypass success/failure rate

Report Template Section


markdown

## Finding V-003: AI Image Deepfake / Identity Fraud

Severity: Critical
Vector 1: Fake LinkedIn profile with AI-generated persona
  - 8/10 connection requests to finance team members accepted
  - 2 team members shared internal information via DM

Vector 2: KYC bypass testing
  - Generated ID document + selfie submitted to verification portal
  - Result: PASSED verification. Account created successfully.
  
Vector 3: CEO face swap on fake wire transfer authorization
  - Swapped CEO face onto authorization document
  - 3/5 finance staff approved the document without verification

Tools Used:
  - InsightFace (face swap)
  - SDXL (fake persona generation)
  - Fooocus (inpainting on ID templates)
  - ExifTool (metadata removal)

Remediation:
  1. Deploy deepfake image detection (Sightengine, Deepware)
  2. Implement out-of-band verification for document-based requests
  3. Enhance KYC with liveness detection (challenge-response video)
  4. Train staff on AI-generated image awareness
  5. Restrict LinkedIn connection acceptance to verified profiles only

Enroll In Online Cybersecurity & Hacking Classes/Courses | Black Hat HQ

Comments


bottom of page