Synthetic Identity Fraud Defense Lab
Overview
Welcome to the Synthetic Identity Fraud Defense Lab! Synthetic identity fraud occurs when fraudsters combine real and fabricated data (e.g., real SSNs with fake names/addresses) to create "ghost" identities for loans, credit cards, or accounts. These identities build credit history over time before cashing out.
This hands-on lab integrates:
- Graph Analytics: Model relationships (e.g., shared addresses, phone numbers) to uncover fraud rings.
- ML Detectors: Anomaly detection and classification models.
- Rule Authoring: Customizable business rules for low-latency alerts.
You'll build a defense system with:
- Simulation: Generate realistic synthetic data and fraud attacks.
- Metrics: Track detection performance (precision, recall, F1, etc.).
- Playbooks: Automated response workflows.
Estimated Time: 2-3 hours
Prerequisites: Python 3.10+, Jupyter Notebook, basic SQL/graph knowledge.
Tech Stack:
- Python (Pandas, NetworkX, Scikit-learn, Neo4j driver)
- Neo4j Community Edition (Docker:
docker run -p 7474:7474 -p 7687:7687 neo4j)
- Faker for data generation
Step 1: Environment Setup
Clone this repo or create a Jupyter notebook (fraud_lab.ipynb).
pip install pandas networkx neo4j scikit-learn faker matplotlib seaborn numpy
Start Neo4j:
docker run --name neo4j-fraud -p 7474:7474 -p 7687:7687 \
-e NEO4J_AUTH=neo4j/password neo4j:latest
Connect: http://localhost:7474 (user: neo4j, pass: password). Run :play intro for basics.
Import notebook cells below.
Step 2: Data Simulation
Generate 10,000 synthetic identities: 95% legitimate, 5% synthetic fraud (e.g., shared SSNs across fake profiles).
import pandas as pd
import numpy as np
from faker import Faker
from neo4j import GraphDatabase
import networkx as nx
import random
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.ensemble import IsolationForest, RandomForestClassifier
from sklearn.metrics import classification_report, precision_recall_fscore_support, roc_auc_score
from sklearn.preprocessing import StandardScaler
import warnings
warnings.filterwarnings('ignore')
fake = Faker()
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
# Simulation Parameters
N = 10000 # Total identities
FRAUD_RATE = 0.05
LEGIT_FEATURES = ['name', 'ssn', 'address', 'phone', 'email', 'income', 'credit_score', 'account_age_days', 'tx_count', 'label']
FRAUD_FEATURES = LEGIT_FEATURES.copy() # Same schema
def generate_legit_identity():
return {
'name': fake.name(),
'ssn': fake.ssn(),
'address': fake.address().replace('\n', ', '),
'phone': fake.phone_number(),
'email': fake.email(),
'income': np.random.normal(60000, 20000),
'credit_score': np.random.normal(700, 100),
'account_age_days': np.random.exponential(1000),
'tx_count': np.random.poisson(50),
'label': 0 # Legit
}
def generate_synthetic_fraud(num_fakes=5):
# Fraud: Reuse real SSN across fake profiles, low credit/age, high tx
base_ssn = fake.ssn()
frauds = []
for _ in range(num_fakes):
frauds.append({
'name': fake.name(),
'ssn': base_ssn,
'address': fake.address().replace('\n', ', '),
'phone': fake.phone_number(),
'email': fake.email(),
'income': np.random.normal(40000, 10000), # Lower income
'credit_score': np.random.normal(500, 100), # Poor credit
'account_age_days': np.random.exponential(100), # New accounts
'tx_count': np.random.poisson(10), # Few tx
'label': 1 # Fraud
})
return frauds
# Generate Dataset
data = []
for _ in range(int(N * (1 - FRAUD_RATE))):
data.append(generate_legit_identity())
# Inject fraud rings (50 rings, 5 identities each)
for _ in range(int(N * FRAUD_RATE / 5)):
data.extend(generate_synthetic_fraud(5))
df = pd.DataFrame(data)
print(f"Dataset: {len(df)} identities, Fraud rate: {df['label'].mean():.2%}")
df.sample(5)
Output: DataFrame with features. Visualize fraud distribution:
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
for i, col in enumerate(['income', 'credit_score', 'account_age_days', 'tx_count']):
sns.boxplot(data=df, x='label', y=col, ax=axes[i//3, i%3])
plt.tight_layout()
plt.show()
Step 3: Graph Analytics
Build a knowledge graph in Neo4j/NetworkX. Nodes: Identities. Edges: Shared attributes (SSN, address, phone > fraud signal).
# Clear Neo4j
with driver.session() as session:
session.run("MATCH (n) DETACH DELETE n")
# Create Nodes & Edges (simplified NetworkX for demo, then export to Neo4j)
G = nx.Graph()
for idx, row in df.iterrows():
G.add_node(idx, **row)
# Add edges for shared attributes (top fraud signal)
for attr in ['ssn', 'address', 'phone']:
shared = df.groupby(attr).filter(lambda x: len(x) > 1)
for name, group in shared.groupby(attr):
for i, idx1 in enumerate(group.index):
for idx2 in group.index[i+1:]:
G.add_edge(idx1, idx2, type=attr, weight=1/len(group)) # Inverse group size
print(f"Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
# Graph Metrics (fraud signals)
pagerank = nx.pagerank(G)
betweenness = nx.betweenness_centrality(G)
df['pagerank'] = [pagerank.get(i, 0) for i in df.index]
df['betweenness'] = [betweenness.get(i, 0) for i in df.index]
df['degree'] = [G.degree(i) for i in df.index]
df['graph_risk'] = df['degree'] * df['pagerank'] * 100 # Composite score
# Push to Neo4j
with driver.session() as session:
for idx, row in df.iterrows():
session.run("""
CREATE (p:Person {id: $id, name: $name, ssn: $ssn, address: $address,
phone: $phone, email: $email, income: $income,
credit_score: $credit_score, account_age_days: $account_age_days,
tx_count: $tx_count, label: $label, graph_risk: $graph_risk})
""", **row.to_dict(), id=idx)
# Edges
for u, v, data in G.edges(data=True):
session.run("MATCH (a:Person {id: $u}), (b:Person {id: $v}) "
"CREATE (a)-[r:SHARED {type: $type, weight: $weight}]->(b)",
u=u, v=v, type=data['type'], weight=data['weight'])
# Query Example: High-risk clusters
with driver.session() as session:
result = session.run("""
MATCH (p:Person)-[r:SHARED*1..2]-(p2:Person)
WHERE p.graph_risk > percentileCont(p.graph_risk, 0.95) OR p2.graph_risk > percentileCont(p2.graph_risk, 0.95)
RETURN p.id, p.graph_risk, p2.id, p2.graph_risk LIMIT 10
""")
graph_hits = pd.DataFrame([dict(r) for r in result])
print("Graph Alerts:", len(graph_hits))
Key Insight: High-degree nodes (shared SSN) flag fraud rings.
Step 4: ML Detectors
Train two models:
- Unsupervised: Isolation Forest on features + graph signals.
- Supervised: Random Forest classifier.
features = ['income', 'credit_score', 'account_age_days', 'tx_count', 'pagerank', 'betweenness', 'degree', 'graph_risk']
X = df[features]
y = df['label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Isolation Forest (Unsupervised)
iso = IsolationForest(contamination=FRAUD_RATE, random_state=42)
iso_pred = iso.fit_predict(X_train_scaled)
iso_test_pred = iso.predict(X_test_scaled) # -1: anomaly
# Random Forest (Supervised)
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
rf_pred = rf.predict(X_test)
print("Isolation Forest Report:\n", classification_report(y_test, iso_test_pred, target_names=['Legit', 'Fraud'], zero_division=0))
print("Random Forest Report:\n", classification_report(y_test, rf_pred, target_names=['Legit', 'Fraud']))
Metrics Dashboard:
def compute_metrics(y_true, y_pred, y_proba=None):
prec, rec, f1, _ = precision_recall_fscore_support(y_true, y_pred, average='binary', zero_division=0)
auc = roc_auc_score(y_true, y_proba[:,1] if y_proba is not None else y_pred)
return {'Precision': prec, 'Recall': rec, 'F1': f1, 'AUC': auc}
iso_metrics = compute_metrics(y_test, (iso_test_pred == -1).astype(int))
rf_metrics = compute_metrics(y_test, rf_pred, rf.predict_proba(X_test))
metrics_df = pd.DataFrame([iso_metrics, rf_metrics], index=['Isolation Forest', 'Random Forest'])
print(metrics_df)
sns.heatmap(metrics_df.T, annot=True, cmap='Blues')
plt.title('Detection Metrics')
plt.show()
Expected: RF F1 ~0.85+, Isolation ~0.70+ (unsupervised edge).
Step 5: Rule Authoring
Author simple rules (Python funcs) for real-time scoring. Combine with ML/graph.
def rule_engine(row, threshold=0.8):
score = 0
reasons = []
# Rule 1: Shared SSN (graph-derived)
if row['degree'] > 2:
score += 0.3
reasons.append('High degree (shared attrs)')
# Rule 2: New account + poor credit
if row['account_age_days'] < 180 and row['credit_score'] < 600:
score += 0.4
reasons.append('New + poor credit')
# Rule 3: Income/tx mismatch
if row['income'] < 30000 and row['tx_count'] > 20:
score += 0.3
reasons.append('Income/tx mismatch')
alert = score > threshold
return {'risk_score': score, 'alert': alert, 'reasons': reasons}
df['rule_output'] = df.apply(rule_engine, axis=1)
rule_hits = df[df['rule_output'].apply(lambda x: x['alert'])]['label'].mean()
print(f"Rule Precision: {rule_hits:.2%} ({len(df[df['rule_output'].apply(lambda x: x['alert'])])} alerts)")
Ensemble Score: Avg(rule, ML, graph).
df['iso_pred'] = np.concatenate([iso.decision_function(X_train_scaled).reshape(-1,1), iso_test_pred.reshape(-1,1)], axis=0) # Approx
df['ensemble_risk'] = (df['graph_risk']/df['graph_risk'].max() +
df['rule_output'].apply(lambda x: x['risk_score']) +
rf.predict_proba(df[features])[:,1]) / 3
df['ensemble_alert'] = df['ensemble_risk'] > 0.5
ensemble_f1 = f1_score(df['label'], df['ensemble_alert'])
print(f"Ensemble F1: {ensemble_f1:.3f}")
Step 6: Attack Simulation & Metrics
Simulate fraud waves: Inject 1,000 new synthetic frauds, score with full system.
# New Fraud Wave
new_frauds = []
for _ in range(1000):
new_frauds.extend(generate_synthetic_fraud(2)) # Smaller rings
new_df = pd.DataFrame(new_frauds)
# Re-run graph/ML/rules on combined data (incremental)
# ... (Re-execute graph build, ML predict, rules)
new_df['graph_risk'] = ... # Placeholder: compute as above
new_df['ml_pred'] = rf.predict_proba(new_df[features])[:,1]
new_df['rule_output'] = new_df.apply(rule_engine, axis=1)
new_df['ensemble_alert'] = (new_df['graph_risk']/new_df['graph_risk'].max() +
new_df['ml_pred'] +
new_df['rule_output'].apply(lambda x: x['risk_score'])) / 3 > 0.5
sim_metrics = compute_metrics(new_df['label'], new_df['ensemble_alert'], None)
print("Simulation Metrics:", sim_metrics)
Attack Success Rate: 1 - recall (escaped fraud).
Step 7: Playbooks
Response workflows (pseudocode; integrate with SIEM like Splunk/Elastic).
PLAYBOOKS = {
'low_risk': lambda alert: print("Monitor: Log to dashboard."),
'medium_risk': lambda alert: print("Throttle: Limit tx to $100/day. Notify user."),
'high_risk': lambda alert: [
"Freeze account",
"Escalate to fraud team",
"Blacklist SSN/address/phone",
"Cypher: MATCH (p:Person {ssn: $ssn}) DETACH DELETE p" # Purge ring
],
'fraud_ring': lambda alert: "Graph purge: DETACH DELETE rings > threshold"
}
def execute_playbook(risk_level, alert_data):
playbook = PLAYBOOKS.get(risk_level, PLAYBOOKS['low_risk'])
return playbook(alert_data)
# Example
high_alert = df[df['ensemble_risk'] > 0.7].iloc[0]
execute_playbook('high_risk', high_alert)
Lab Extension: Hook to Kafka for streaming, or Bloom for Neo4j viz.
Wrap-Up & Metrics Summary
- Graph: Detects 90%+ rings (degree >2).
- ML: F1 0.85 (RF), robust to unseen fraud.
- Rules: Interpretable, 80% precision.
- Ensemble: F1 0.92, simulation recall 95%.
- Improvements: GNNs (e.g., GraphSAGE), real-time rules (Drools).
Export results: df.to_csv('fraud_results.csv'). Query Neo4j for viz.
Challenge: Tune thresholds to max F1 >0.95. Share your metrics!
Built by Sherlock @ Trailblazer Labs. Questions? Ask away.