Data Leakage and Privacy Attacks

Updated · 9 min read
hardPython 3.13aisecurityprivacydata-leakagememorizationredaction

Data leakage in AI means private or confidential information ending up where it shouldn't: in another user's answer, in logs, with an outside provider, or inside a model's weights where it can later be pulled out. AI makes leaks easier because models read huge amounts of text, can memorize parts of what they were trained on, and will happily repeat whatever is in their context if asked the right way.

How Data Leaks

PathDescription
Prompts sent to a providerIt is used every time you call a hosted model; check what the provider stores and how long
Logs and analyticsIt is used to debug and monitor, and often quietly collects names, emails and account numbers
Retrieval without permissionsA RAG system that searches all documents can show one user another user's files
Memorized training dataModels can repeat rare text from their training data word for word, including personal data
Fine-tuning dataPrivate examples used for fine-tuning can be extracted from the tuned model
Prompt and context extractionSecrets and other users' data in the context can be asked for directly

Example: Models Memorize Text

Models don't store documents, but they can memorize text they saw many times. This program gives the base SmolLM2-135M model the start of three texts and checks whether it continues them word for word.

The programs that run a model need pip install torch transformers; they use small open SmolLM2 models from Hugging Face, standing in for the model behind Campus Helper. Download and loading messages are left out of the output shown.

Models can recite what they saw often; redact before anything leaves
Python
from transformers import AutoModelForCausalLM, AutoTokenizer
 
# The base model, which was pretrained on web text (see "Pretraining")
name = "HuggingFaceTB/SmolLM2-135M"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name).eval()
 
texts = {   # (start given to the model, how the real text continues)
    "US Declaration of Independence": ("We hold these truths to be self-evident, that all men are created",
                                       " equal, that they are endowed by their Creator with certain unalienable Rights,"),
    "Gettysburg Address": ("Four score and seven years ago our fathers brought forth",
                           " on this continent, a new nation, conceived in Liberty,"),
    "A sentence written for this lesson": ("Srihitha's library card number at the Dallas branch is",
                                           " 4417-2290-1185, and her PIN is 9921."),
}
for title, (start, real) in texts.items():
    ids = tokenizer(start, return_tensors="pt").input_ids
    out = model.generate(ids, max_new_tokens=20, do_sample=False, pad_token_id=tokenizer.eos_token_id)
    continuation = tokenizer.decode(out[0, ids.shape[1]:], skip_special_tokens=True)
    real_words, model_words = real.split(), continuation.split()
    same = 0
    for a, b in zip(real_words, model_words):
        if a.strip(",.").lower() != b.strip(",.").lower():
            break
        same += 1
    print(f"{title}\n  model: {continuation.strip()[:80]!r}\n  first {same} of {len(real_words)} words match the real text\n")
Output
US Declaration of Independence
  model: 'equal, that they are endowed by their Creator with certain unalienable Rights, t'
  first 12 of 12 words match the real text
 
Gettysburg Address
  model: 'a new nation, and that nation is the United States of America.\n\nThe United State'
  first 0 of 9 words match the real text
 
A sentence written for this lesson
  model: '1000000000000000000'
  first 0 of 6 words match the real text

Explanation:

  • The Declaration of Independence: all 12 words match. This famous text appears on thousands of web pages, so the model saw it many times in pretraining and memorized it.
  • The Gettysburg Address: 0 of 9 words match exactly, although the model jumps ahead to "a new nation". It has seen the text less often, so it remembers fragments, not the whole.
  • The made-up sentence: 0 of 6. The library card number was written for this lesson and was never in the training data, so the model invents a number instead.
  • The risk: if a real person's card number or address had appeared many times in the training data, a model could repeat it in the same way. Researchers have extracted names, phone numbers and email addresses from real models like this. That is why training and fine-tuning data must be cleaned of personal data first.

Example: Redacting Before Anything Leaves

The simplest protection is to remove personal data before it is logged, stored or sent to an outside model. This program replaces emails, phone numbers, Social Security numbers and card numbers with tags.

Python
import re
 
# Redact personal data BEFORE a message is logged, stored, or sent to an outside model
PATTERNS = [
    ("EMAIL", r"[\w.+-]+@[\w-]+\.[\w.]+"),
    ("PHONE", r"\(?\b\d{3}\)?[-. ]?\d{3}[-. ]\d{4}\b"),
    ("SSN", r"\b\d{3}-\d{2}-\d{4}\b"),
    ("CARD", r"\b(?:\d{4}[- ]?){3}\d{4}\b"),
]
 
def redact(text):
    found = []
    for label, pattern in PATTERNS:
        text, n = re.subn(pattern, f"[{label}]", text)
        if n:
            found.append(f"{label} x{n}")
    return text, found
 
messages = [
    "Hi, I'm Navika. Please email me at navika.parent@example.com or call (214) 555-0137 about the fee.",
    "My card 4111 1111 1111 1111 was charged twice for the field trip.",
    "For the waiver form, my SSN is 123-45-6789.",
    "What time is lunch?",
    "Advitha's student number is 20481 and she is in room 104.",
]
for m in messages:
    clean, found = redact(m)
    print(f"{clean}\n   removed: {', '.join(found) or 'nothing'}")
Output
Hi, I'm Navika. Please email me at [EMAIL] or call [PHONE] about the fee.
   removed: EMAIL x1, PHONE x1
My card [CARD] was charged twice for the field trip.
   removed: CARD x1
For the waiver form, my SSN is [SSN].
   removed: SSN x1
What time is lunch?
   removed: nothing
Advitha's student number is 20481 and she is in room 104.
   removed: nothing

Explanation:

  • re.subn replaces every match and counts them, so the program can report what it removed.
  • The email, phone, card and Social Security numbers are replaced with [EMAIL], [PHONE], [CARD] and [SSN]. The questions still make sense for answering, and nothing sensitive reaches the log.
  • "What time is lunch?" is untouched.
  • The last message shows the limits: the name "Advitha" and the student number 20481 are not caught, because no pattern matches them. Real systems add name detection with trained models (named-entity recognition), patterns for their own ID formats, and a person reviewing samples. Redaction reduces leaks; it doesn't guarantee none.

Other Privacy Attacks

AttackWhat it tries to learnDefense
Training data extractionRare text the model memorizedClean and deduplicate training data; test for memorization
Membership inferenceWhether a specific person's record was in the training dataLess overfitting; differential privacy
Cross-user retrievalAnother user's documents through a shared RAG indexApply each user's permissions at search time
Context extractionOther data placed in the promptPut only what this user may see into their prompt
Model inversionApproximate training examples from a model's outputsLimit output detail; rate-limit queries

Common Mistakes

Logging full prompts and answers by default. Logs are the most common leak; redact and limit retention.

One shared search index for everyone. Retrieval must respect who is allowed to see each document.

Fine-tuning on raw support tickets or emails. They are full of names, addresses and account details.

Thinking redaction catches everything. Patterns miss names and new formats; combine methods and review.

Interview Corner

How can an LLM application leak sensitive data?

Through prompts sent to providers, logs, retrieval that ignores permissions, secrets or other users' data placed in the context, and training or fine-tuning data the model memorized. Each path needs its own control: data terms, redaction, permission-aware retrieval, minimal context and clean training data.

What is training data extraction?

Getting a model to reproduce text it memorized from its training data, sometimes word for word, by giving it the right starting text or asking repeatedly. It is most likely for text that was repeated often or is very distinctive, which is why personal data should be removed and duplicates reduced before training.

Practice

Exercise: better redaction. Add a pattern for student numbers (five digits after the words "student number") and one for US street addresses. Test them on five sentences of your own, including two that should not be changed.

Check your understanding:

  1. Why did the model recite the Declaration of Independence but not the made-up card number?
  2. Which personal details did the redaction miss, and why?
  3. How can a RAG system leak one user's data to another?

Quick check: data leakage

4 questions
1How many of the next 12 words of the Declaration did the model reproduce?
2What did the redaction miss in the last message?
3What prevents cross-user leaks in a RAG system?
4When should personal data be removed from training or fine-tuning data?

Key Takeaways

Quick reference

NeedCode or practice
Replace and count matchestext, n = re.subn(pattern, "[EMAIL]", text)
Email pattern[\w.+-]+@[\w-]+\.[\w.]+
Find namesNamed-entity recognition models
Safe retrievalFilter documents by the user's permissions before search
Fewer leaks in logsRedact, restrict access, delete on a schedule

Was this tutorial helpful?

Lesson 166 of 186