TExcelTAD

Security of ML Systems

A model service is an ordinary web service with all the ordinary risks (injection, leaked credentials, vulnerable dependencies) plus a few of its own. The model file can carry code. The training data can be manipulated so that the model learns what an attacker wants. Inputs can be nudged so that the model changes its answer. And the answers themselves leak information: about the training data, and about the model, which someone can copy by asking enough questions. This lesson walks through those threats with small, safe demonstrations and the defences that go with each.

Threat 1: model files that run code

Python's pickle (and joblib, which uses it) does not store data, it stores instructions to rebuild objects, and one of those instructions is "call this function with these arguments". Whoever writes a pickle file decides which function. Loading an untrusted pickle is therefore running untrusted code, with the permissions of the loading process: reading your credentials, opening a shell, changing other files. Saving models covered pickle as a format; here is why it is a security boundary.

The demonstration below is harmless: the payload only calls print. A real attacker would put os.system or exec there.

python · try it yourself
import io
import pickle
import pickletools

class LooksLikeAModel:
    def __reduce__(self):                        # tells pickle how to "rebuild" this object
        return (print, ("!! this line was run by pickle.loads, not by your code",))

payload = pickle.dumps(LooksLikeAModel())
imports = [arg for op, arg, pos in pickletools.genops(payload) if op.name == "SHORT_BINUNICODE"]
print("strings in the payload:", imports)
obj = pickle.loads(payload)                      # loading = calling print(...)
print("pickle.loads returned:", obj)

class AllowListUnpickler(pickle.Unpickler):
    """Refuse every global that is not explicitly allowed."""
    ALLOWED = {("collections", "OrderedDict")}
    def find_class(self, module, name):
        if (module, name) in self.ALLOWED:
            return super().find_class(module, name)
        raise pickle.UnpicklingError(f"blocked {module}.{name}")

try:
    AllowListUnpickler(io.BytesIO(payload)).load()
except pickle.UnpicklingError as e:
    print("allow-list unpickler:", e)
strings in the payload: ['builtins', 'print', '!! this line was run by pickle.loads, not by your code']
!! this line was run by pickle.loads, not by your code
pickle.loads returned: None
allow-list unpickler: blocked builtins.print

The payload names builtins.print in plain sight, which is what pickle scanners look for, and pickle.loads ran it before returning anything. An allow-list unpickler blocks it, but real scikit-learn or PyTorch pickles reference dozens of classes, so a hand-written allow-list is fragile. The practical defences:

  • Load pickles only from sources you control, and verify they are the files you produced (hashes and signatures, next section). Never load a model uploaded by a user or downloaded from a hub without checks.
  • Prefer formats without code: ONNX for whole models, safetensors for neural network weights (tensors and a JSON header, nothing executable), skops.io for scikit-learn (an allow-list loader that reports unknown types). torch.load defaults to weights_only=True since PyTorch 2.6, which also restricts what it loads.
  • Scan and sandbox model files from outside (tools such as picklescan or Protect AI's modelscan list the imports in a pickle), and load them in a process without secrets or network.

Threat 2: the model supply chain

A model release is a chain of artifacts: training data, code, base images, pretrained weights, the trained model file, the serving image. Each link can be swapped. The defences are the ones of software supply chain security, applied to model files too:

  • Pin by hash. Record the SHA-256 of every artifact when it is produced (the registry or a manifest stores it) and refuse to load a file whose hash differs (hash pinning).
  • Sign artifacts and images, and verify signatures at deploy time (cosign); record provenance (which pipeline, from which commit and data version, built this file; provenance).
  • Pretrained models are dependencies. Pin the exact revision (a commit hash on a model hub, not "latest"), read their licence and model card, and scan them like any third-party package.
python · try it yourself
import hashlib
import pickle
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
model = LogisticRegression().fit(X[:1500], y[:1500])
with open("risk-model-v7.pkl", "wb") as f:
    pickle.dump(model, f)

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()

manifest = {"risk-model-v7.pkl": sha256("risk-model-v7.pkl")}   # written by the training pipeline

def load_verified(path):
    actual = sha256(path)
    if actual != manifest[path]:
        raise RuntimeError(f"hash mismatch for {path}: refusing to load")
    with open(path, "rb") as f:
        return pickle.load(f)

m = load_verified("risk-model-v7.pkl")
print("verified load, test accuracy:", round(m.score(X[1500:], y[1500:]), 3))

with open("risk-model-v7.pkl", "r+b") as f:     # someone changes one byte of the file
    f.seek(200); b = f.read(1); f.seek(200); f.write(bytes([b[0] ^ 1]))
try:
    load_verified("risk-model-v7.pkl")
except RuntimeError as e:
    print(e)
verified load, test accuracy: 0.844
hash mismatch for risk-model-v7.pkl: refusing to load

A hash proves the file is the one recorded in the manifest. It does not prove the manifest is genuine: that is what a signature over the manifest (or the artifact) adds, with the key held by the pipeline, not by the people who can write to the bucket.

Threat 3: adversarial examples

A small, targeted change to an input can flip a model's answer. For a model with a gradient, the fast gradient sign method (FGSM) moves each feature by a fixed step eps in the direction that increases the loss: x_adv = x + eps * sign(gradient of the loss with respect to x). For logistic regression the gradient is simply (p - y) * w, the prediction error times the weights, so the attack pushes every feature against the true class at once. The from-scratch version, on standardised features:

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
scaler = StandardScaler().fit(X[:1500])
X_train, X_test = scaler.transform(X[:1500]), scaler.transform(X[1500:])
y_train, y_test = y[:1500], y[1500:]

w, b = np.zeros(8), 0.0                           # logistic regression by gradient descent
for _ in range(2000):
    p = 1 / (1 + np.exp(-(X_train @ w + b)))
    w -= 0.1 * X_train.T @ (p - y_train) / len(y_train)
    b -= 0.1 * np.mean(p - y_train)

def predict(X):
    return (X @ w + b > 0).astype(int)

p_test = 1 / (1 + np.exp(-(X_test @ w + b)))
grad = (p_test - y_test)[:, None] * w[None, :]    # d(log-loss)/dx for every test row
rng = np.random.default_rng(0)
print(f"test rows: {len(y_test)}")
print(" eps   accuracy FGSM   accuracy random +-eps")
for eps in (0.0, 0.1, 0.2, 0.3, 0.5):
    acc_adv = (predict(X_test + eps * np.sign(grad)) == y_test).mean()
    acc_rnd = (predict(X_test + eps * rng.choice([-1, 1], X_test.shape)) == y_test).mean()
    print(f" {eps:.1f}   {acc_adv:.3f}           {acc_rnd:.3f}")
test rows: 500
 eps   accuracy FGSM   accuracy random +-eps
 0.0   0.844           0.844
 0.1   0.790           0.848
 0.2   0.706           0.842
 0.3   0.606           0.836
 0.5   0.400           0.796

On 500 test rows, the model's accuracy is 0.844. A step of 0.3 standard deviations per feature in the FGSM direction drops it to 0.606, and 0.5 to 0.400, worse than a coin. Random steps of the same size barely matter (0.836 at 0.3, 0.796 at 0.5). The attack is not about noise; it is about direction, and for a linear model that direction is known to anyone who knows or can estimate the weights. Whether 0.3 SD is "small" depends on the feature: for income it may be a payslip edit, for age it is impossible.

Defences are partial: input validation (reject values outside plausible ranges and impossible combinations, as the guard in rollback and fallbacks does), features an applicant cannot easily change, adversarial training (train on perturbed examples), monitoring for repeated near-identical queries, and a human review band around the threshold. Robustness testing measures how much perturbation a model tolerates.

Threat 4: data poisoning

If attackers can influence the training data (user-generated content, feedback buttons, crowd labels, scraped web data), they can poison it: flip labels in one region so the model learns a blind spot, or plant a backdoor, a trigger pattern (a rare token, a pixel patch, a specific merchant id) that makes the model output the attacker's class whenever it appears, while accuracy on clean data stays normal. Defences: control and log who can write training data (data versioning gives an audit trail), validate incoming batches (data validation), look for clusters of suspicious labels, cap the influence of any single source or user, and gate every retrained model on a trusted, curated test set, as the guarded learner in replay and rollback did with a corrupted batch.

Threat 5: what the outputs leak

Every answer gives away a little. Membership inference asks whether a given record was in the training set: overfitted models are more confident on rows they memorised, and that difference is the signal. Model extraction queries the API many times and trains a copy, a "surrogate", on the answers, stealing the model or preparing better adversarial examples against it. Both get easier the more precise the outputs are and the more queries are allowed.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

X, y = make_classification(n_samples=1200, n_features=8, n_informative=5, flip_y=0.2, random_state=0)
X_mem, y_mem, X_out, y_out = X[:400], y[:400], X[400:800], y[400:800]   # members / non-members
X_test, y_test = X[800:], y[800:]
is_member = np.r_[np.ones(400), np.zeros(400)]

def attack_auc(model, transform):
    """Attacker's score: the (released) probability of the true label."""
    s = [transform(model.predict_proba(Xs))[np.arange(len(ys)), ys] for Xs, ys in ((X_mem, y_mem), (X_out, y_out))]
    return roc_auc_score(is_member, np.r_[s[0], s[1]])

full = lambda p: p
rounded = lambda p: np.round(p, 1)
label_only = lambda p: (p == p.max(axis=1, keepdims=True)).astype(float)

overfit = RandomForestClassifier(n_estimators=100, random_state=0).fit(X_mem, y_mem)
regular = RandomForestClassifier(n_estimators=100, min_samples_leaf=20, random_state=0).fit(X_mem, y_mem)
print("membership inference (AUC 0.5 = attacker learns nothing), 400 members vs 400 non-members")
for name, model in (("overfit forest", overfit), ("min_samples_leaf=20", regular)):
    print(f"  {name:20s} test acc {model.score(X_test, y_test):.3f} | AUC full {attack_auc(model, full):.3f}"
          f"  rounded {attack_auc(model, rounded):.3f}  label-only {attack_auc(model, label_only):.3f}")

rng = np.random.default_rng(0)
victim = LogisticRegression().fit(X[:800], y[:800])
print("model extraction: surrogate trained on the API's labels for random queries")
for n_queries in (20, 100, 1000):
    Q = rng.normal(0, 2, size=(n_queries, 8))
    surrogate = LogisticRegression().fit(Q, victim.predict(Q))
    agree = (surrogate.predict(X_test) == victim.predict(X_test)).mean()
    print(f"  {n_queries:5d} queries: agrees with the victim on {agree:.3f} of 400 test rows")
membership inference (AUC 0.5 = attacker learns nothing), 400 members vs 400 non-members
  overfit forest       test acc 0.812 | AUC full 0.752  rounded 0.742  label-only 0.588
  min_samples_leaf=20  test acc 0.760 | AUC full 0.521  rounded 0.519  label-only 0.526
model extraction: surrogate trained on the API's labels for random queries
     20 queries: agrees with the victim on 0.917 of 400 test rows
    100 queries: agrees with the victim on 0.993 of 400 test rows
   1000 queries: agrees with the victim on 1.000 of 400 test rows

The overfit forest (fully grown trees on 400 noisy rows) gives the attacker an AUC of 0.752: given one member and one non-member, it ranks the member higher three times in four, just from the confidence on the true label. Rounding the released probability to one decimal changes almost nothing (0.742). Releasing only the label cuts it to 0.588. The regularised forest leaks almost nothing at any precision (0.519 to 0.526), but here it costs accuracy: 0.760 against 0.812 on the 400 test rows. Extraction needs no probabilities at all: a surrogate trained on 100 random queries, labels only, agrees with the victim on 0.993 of the test rows, and on all of them after 1,000 queries. Rounding defends against neither attack well; only limiting and watching queries raises the cost of extraction.

Defences against leakage:

  • Release less: return a decision or a coarse score instead of a full-precision probability, unless the client needs calibrated probabilities.
  • Regularise: a model that does not memorise its training rows leaks less, and usually generalises better. For strong guarantees, train with differential privacy (DP-SGD), at a cost in accuracy.
  • Rate-limit and monitor per client (rate limiting): extraction needs many queries, often unusual ones (random points far from real data). Require authentication, set quotas, and alert on query patterns that look like a sweep.

Secrets and the rest of the service

Model services need credentials: the registry, the feature store, object storage, the database for the prediction log. They follow the same secrets policy as any service: never in the image, the code, the notebook or the model artifact (a pickled object can carry an API key that was an attribute of a training helper); injected at runtime from a secret store (Kubernetes secrets), scoped to what each component needs, rotated. Training notebooks and experiment trackers are a common leak: logged parameters and artifacts are readable by everyone with access to the tracking server. And the service itself needs the ordinary hardening: image security and scanning, authentication on the prediction endpoint, request size limits, and schema validation of every input before it reaches the model.

Pitfalls

  • "It is only a model file." A pickle is a program. Treat model files from outside like executables.
  • Trusting a hub's name. A model repository with a familiar name can be a typo-squat or have been changed since you looked; pin revisions and hashes.
  • Full-precision probabilities for everyone. Precise outputs help attackers more than most clients.
  • No per-client limits. Without quotas, extraction and membership attacks cost the attacker only time.
  • Security checks only at training time. Verify hashes and signatures at load time, in the serving process, every time.

Practice

  1. Why does an allow-list unpickler not solve the pickle problem for a typical scikit-learn model in practice?
  2. In the FGSM example, compare the accuracy at eps = 0.3 with FGSM and with random noise of the same size. What does the difference tell you about the threat?
  3. In the leakage example, which change reduced the membership inference AUC most, and what did it cost in test accuracy?
Answers
  1. A fitted pipeline references many classes and functions (NumPy array reconstruction, scikit-learn estimator classes, sometimes your own transformers), so the allow-list must be long and kept in sync with library versions, and any allowed callable that can be misused reopens the hole. Formats designed without code (ONNX, safetensors, skops with its type checks) are the robust fix.
  2. At eps = 0.3, FGSM leaves 0.606 accuracy and random noise 0.836. The same budget in the worst direction for every row does far more damage than in a random one, so robustness to random noise says little about robustness to an attacker.
  3. Regularisation (min_samples_leaf=20): AUC 0.752 down to 0.521, close to the 0.5 of a blind guess, at a cost of 0.052 in test accuracy (0.812 to 0.760). Label-only outputs cut the AUC of the overfit forest to 0.588 without changing its accuracy, but they break clients that need probabilities. The two can be combined.

Test yourself

Why is loading an untrusted pickle file dangerous?

  1. It may be corrupted
  2. Unpickling can call arbitrary functions chosen by whoever wrote the file
  3. It uses too much memory
  4. Pickle files are not compressed

What does a SHA-256 hash recorded in a model manifest protect against?

  1. Adversarial examples
  2. A model file being changed or swapped after it was produced
  3. Membership inference
  4. Concept drift

For logistic regression, in which direction does FGSM move an input?

  1. Randomly
  2. By eps per feature in the sign of (p - y) * w, the direction that increases the loss
  3. Towards the class mean
  4. Along the first principal component

Which measure most directly slows down model extraction through the API?

  1. Rounding the scores to one decimal
  2. Authentication, per-client rate limits and monitoring of query patterns
  3. A larger model
  4. Retraining more often