Model extraction defense is an economics problem. You cannot stop an attacker from querying a public API, but you can make each query leak less, make systematic querying visible, and make a stolen copy measurably worse than the original. This sub-skill builds on the extraction probes from its parent and turns each leak into a control with a before and after measurement. Stay inside the agreed query budget, use test endpoints and test keys, and never build a working clone beyond the proof point.
Quick Workflow
- Measure the baseline leak. Record what one prediction returns, full probabilities, top label only, or calibrated scores, and how accurately a small substitute can be trained from a bounded query set.
- Rank the leaks by cost to the attacker. Full probability vectors and confidence scores leak the most, per query pricing and rate limits change the price, and monitoring changes the risk.
- Apply the cheapest high impact control first. Usually output rounding or truncation, then per key rate limits, then query pattern detection.
- Re-run the same bounded extraction probe against the defended endpoint and compare substitute accuracy before and after.
- Test watermarking separately. Check that a watermark survives in a substitute trained on watermarked outputs and that it does not degrade legitimate predictions.
- Tune rate limits against legitimate traffic. A limit that blocks real users will be rolled back, which restores the leak, so measure the legitimate peak first.
- Report the new cost math. Queries needed times price, plus the substitute accuracy drop, is the evidence the defense works.
1. Measuring the baseline leak
Do not guess what the API leaks. Query it once, inspect the full response, and run a small bounded probe before proposing any control.
# What does one prediction return on the test endpoint
curl -s -X POST 'https://target.example/api/predict' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $TOKEN" \
-d '{"features":[0.5,0.2,0.9,0.1]}' | python3 -m json.tool
# Full probability vector = high leakage, top label leakage,
# rounded scores = medium leakage, exact scores = high leakage.
#!/usr/bin/env python3
"""Bounded substitute accuracy probe, before and after a defense."""
import json, urllib.request
ENDPOINT = "https://target.example/api/predict"
TOKEN = "REPLACE_WITH_TEST_TOKEN"
BUDGET = 500 # agreed query budget, do not exceed
def predict(features):
req = urllib.request.Request(
ENDPOINT, data=json.dumps({"features": features}).encode(),
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {TOKEN}"})
with urllib.request.urlopen(req, timeout=30) as r:
return json.load(r)
# Collect a labeled set, then compare how well a trivial substitute
# (nearest labeled neighbor) predicts a held out probe set.
import random
random.seed(7)
labeled = []
for _ in range(BUDGET):
x = [round(random.random(), 2) for _ in range(4)]
labeled.append((x, predict(x)))
def nearest_label(x):
best, best_d = None, float("inf")
for lx, ly in labeled:
d = sum((a - b) ** 2 for a, b in zip(x, lx))
if d < best_d:
best, best_d = ly, d
return best
def top_label(resp):
if isinstance(resp, dict):
if "label" in resp:
return resp["label"]
probs = resp.get("probabilities") or resp.get("scores") or []
if probs:
return max(range(len(probs)), key=lambda i: probs[i])
return resp
holdout = []
for _ in range(100):
x = [round(random.random(), 2) for _ in range(4)]
holdout.append((x, top_label(predict(x))))
hits = sum(1 for x, y in holdout if top_label(nearest_label(x)) == y)
print(f"substitute accuracy on holdout: {hits}/{len(holdout)}")
print("Run this probe before and after each defense, with the same seed.")
2. Output rounding and truncation
Rounding is the highest value control for most classification APIs. It costs almost nothing to legitimate users, who rarely need four decimal places, and it removes the gradient signal that makes extraction efficient.
# Defense sketch: round probabilities before returning them.
# Apply this on the server, never trust the client to round.
def defended_response(probabilities):
rounded = [round(p, 2) for p in probabilities]
# Renormalize so the rounded values still sum to 1.
total = sum(rounded) or 1.0
return {"label": max(range(len(rounded)), key=lambda i: rounded[i]),
"probabilities": [round(p / total, 2) for p in rounded]}
print(defended_response([0.7314, 0.1982, 0.0704]))
# Before defense, an attacker gets 0.7314, after defense they get 0.73.
# Test the substitute probe again and record how much accuracy it loses.
# Verify rounding on the live test endpoint after deployment
curl -s -X POST 'https://target.example/api/predict' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $TOKEN" \
-d '{"features":[0.5,0.2,0.9,0.1]}' \
| python3 -c "import json,sys; d=json.load(sys.stdin); print(d); assert all(len(str(p).split('.')[-1]) <= 2 for p in d.get('probabilities', [])), 'not rounded'"
3. Query pattern detection and rate limiting
A single user rarely queries a uniform grid over the whole input space. Systematic querying looks different from legitimate traffic, and that difference is detectable without blocking real users.
#!/usr/bin/env python3
"""Flag systematic querying from an API access log (offline analysis)."""
import json, collections
# Each log line: {"key": "api-key-id", "features": [..], "time": "..."}
suspicious = collections.Counter()
per_key = collections.defaultdict(list)
with open("/tmp/predict_log.jsonl") as fh:
for line in fh:
entry = json.loads(line)
per_key[entry["key"]].append(entry["features"])
for key, queries in per_key.items():
# High volume plus near uniform coverage is the extraction signature.
# Legitimate traffic clusters around real inputs, extraction grids do not.
if len(queries) > 1000:
first_feature = [q[0] for q in queries]
spread = max(first_feature) - min(first_feature)
if spread > 0.9:
suspicious[key] += 1
print(f"{key}: {len(queries)} queries, feature spread {spread:.2f} - investigate")
print(f"flagged keys: {len(suspicious)}")
Edge cases
- Legitimate batch users look like extractors. Allowlist known batch keys with their own quota instead of blocking them, and monitor them separately.
- Rounding breaks a downstream consumer that thresholds on exact scores. Agree the rounding precision with consumers before shipping, and test their thresholds.
- An attacker spreads queries across many keys or IPs. Correlate by query pattern and input distribution, not by key alone, and add account level quotas.
- Watermarking changes predictions enough to be noticed. Measure legitimate accuracy before and after, and keep the watermark perturbation below the noise floor of normal use.
- Membership inference survives output rounding. Rounding stops functionality stealing, it does not stop a membership test on an overfit model, so test both attacks after each defense.
- Rate limits are set from averages, not peaks. Measure the legitimate peak hour before choosing a limit, or the first traffic spike becomes an outage that gets the limit removed.
Key references
- MITRE ATLAS AML.T0024 (ML Model Extraction) and AML.T0025 (ML Model Inversion).
- CWE-200 (Exposure of Sensitive Information) for rich prediction outputs.
- OWASP Top 10 for LLM Applications, LLM10 Model Theft, and the OWASP AI security guidance on model extraction.
- NIST AI Risk Management Framework, manage function for deployed model protection.
- Tramèr and coauthors, Stealing Machine Learning Models via Prediction APIs, USENIX Security 2016.
