Data Leakage and Privacy Attacks
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
| Path | Description |
|---|---|
| Prompts sent to a provider | It is used every time you call a hosted model; check what the provider stores and how long |
| Logs and analytics | It is used to debug and monitor, and often quietly collects names, emails and account numbers |
| Retrieval without permissions | A RAG system that searches all documents can show one user another user's files |
| Memorized training data | Models can repeat rare text from their training data word for word, including personal data |
| Fine-tuning data | Private examples used for fine-tuning can be extracted from the tuned model |
| Prompt and context extraction | Secrets 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.
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")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 textExplanation:
- 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.
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'}")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: nothingExplanation:
re.subnreplaces 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
| Attack | What it tries to learn | Defense |
|---|---|---|
| Training data extraction | Rare text the model memorized | Clean and deduplicate training data; test for memorization |
| Membership inference | Whether a specific person's record was in the training data | Less overfitting; differential privacy |
| Cross-user retrieval | Another user's documents through a shared RAG index | Apply each user's permissions at search time |
| Context extraction | Other data placed in the prompt | Put only what this user may see into their prompt |
| Model inversion | Approximate training examples from a model's outputs | Limit 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:
- Why did the model recite the Declaration of Independence but not the made-up card number?
- Which personal details did the redaction miss, and why?
- How can a RAG system leak one user's data to another?
Key Takeaways
Quick reference
| Need | Code or practice |
|---|---|
| Replace and count matches | text, n = re.subn(pattern, "[EMAIL]", text) |
| Email pattern | [\w.+-]+@[\w-]+\.[\w.]+ |
| Find names | Named-entity recognition models |
| Safe retrieval | Filter documents by the user's permissions before search |
| Fewer leaks in logs | Redact, restrict access, delete on a schedule |
Was this tutorial helpful?