From a4548528f9fd5ccd83a5d44c08d2d080323bde1a Mon Sep 17 00:00:00 2001 From: ghislainpiot Date: Wed, 5 Jun 2024 15:09:45 +0000 Subject: [PATCH] Create rule S6985 --- rules/S6985/metadata.json | 2 ++ rules/S6985/python/metadata.json | 25 +++++++++++++++++++++++ rules/S6985/python/rule.adoc | 35 ++++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+) create mode 100644 rules/S6985/metadata.json create mode 100644 rules/S6985/python/metadata.json create mode 100644 rules/S6985/python/rule.adoc diff --git a/rules/S6985/metadata.json b/rules/S6985/metadata.json new file mode 100644 index 00000000000..2c63c085104 --- /dev/null +++ b/rules/S6985/metadata.json @@ -0,0 +1,2 @@ +{ +} diff --git a/rules/S6985/python/metadata.json b/rules/S6985/python/metadata.json new file mode 100644 index 00000000000..85a9d41f6a1 --- /dev/null +++ b/rules/S6985/python/metadata.json @@ -0,0 +1,25 @@ +{ + "title": "Usage of \"torch.load\" can lead to untrusted code execution", + "type": "SECURITY_HOTSPOT", + "status": "ready", + "remediation": { + "func": "Constant\/Issue", + "constantCost": "15min" + }, + "tags": [ + "pytorch", + "machine-learning" + ], + "defaultSeverity": "Major", + "ruleSpecification": "RSPEC-6985", + "sqKey": "S6985", + "scope": "All", + "defaultQualityProfiles": ["Sonar way"], + "quickfix": "infeasible", + "code": { + "impacts": { + "SECURITY": "HIGH" + }, + "attribute": "CONVENTIONAL" + } +} diff --git a/rules/S6985/python/rule.adoc b/rules/S6985/python/rule.adoc new file mode 100644 index 00000000000..8ab31c6acba --- /dev/null +++ b/rules/S6985/python/rule.adoc @@ -0,0 +1,35 @@ +This rule raises an issue when `pytorch.load` is used to load a model. + +== Why is this an issue? + +Under the hood, `torch.load` uses the `pickle` library to load the model and the weights. +If the model comes from an untrusted source, an attacker could inject a malicious payload which would be executed during the deserialization. + +== How to fix it +Use a safer alternative to load the model, such as `safetensors.torch.load_model`. +=== Code examples + +==== Noncompliant code example + +[source,python,diff-id=1,diff-type=noncompliant] +---- +import torch + +model = torch.load('model.pth') # Noncompliant: torch.load is used to load the model +---- + +==== Compliant solution + +[source,python,diff-id=1,diff-type=compliant] +---- +import torch +import safetensors + +model = MyModel() +safetensors.torch.load_model(model, 'model.pth') +---- + +== Resources +=== Documentation + +* Pytorch documentation: https://pytorch.org/tutorials/beginner/saving_loading_models.html#save-load-entire-model[Save/Load Entire Model] \ No newline at end of file