|
| 1 | +# Copyright (c) 2024 Stacklok, Inc. |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +r""" |
| 5 | +========================================== |
| 6 | +B614: Test for unsafe PyTorch load or save |
| 7 | +========================================== |
| 8 | +
|
| 9 | +This plugin checks for the use of `torch.load` and `torch.save`. Using |
| 10 | +`torch.load` with untrusted data can lead to arbitrary code execution, and |
| 11 | +improper use of `torch.save` might expose sensitive data or lead to data |
| 12 | +corruption. A safe alternative is to use `torch.load` with the `safetensors` |
| 13 | +library from hugingface, which provides a safe deserialization mechanism. |
| 14 | +
|
| 15 | +:Example: |
| 16 | +
|
| 17 | +.. code-block:: none |
| 18 | +
|
| 19 | + >> Issue: Use of unsafe PyTorch load or save |
| 20 | + Severity: Medium Confidence: High |
| 21 | + CWE: CWE-94 (https://cwe.mitre.org/data/definitions/94.html) |
| 22 | + Location: examples/pytorch_load_save.py:8 |
| 23 | + 7 loaded_model.load_state_dict(torch.load('model_weights.pth')) |
| 24 | + 8 another_model.load_state_dict(torch.load('model_weights.pth', |
| 25 | + map_location='cpu')) |
| 26 | + 9 |
| 27 | + 10 print("Model loaded successfully!") |
| 28 | +
|
| 29 | +.. seealso:: |
| 30 | +
|
| 31 | + - https://cwe.mitre.org/data/definitions/94.html |
| 32 | + - https://pytorch.org/docs/stable/generated/torch.load.html#torch.load |
| 33 | + - https://github.com/huggingface/safetensors |
| 34 | +
|
| 35 | +.. versionadded:: 1.7.10 |
| 36 | +
|
| 37 | +""" |
| 38 | +import bandit |
| 39 | +from bandit.core import issue |
| 40 | +from bandit.core import test_properties as test |
| 41 | + |
| 42 | + |
| 43 | +@test.checks("Call") |
| 44 | +@test.test_id("B614") |
| 45 | +def pytorch_load_save(context): |
| 46 | + """ |
| 47 | + This plugin checks for the use of `torch.load` and `torch.save`. Using |
| 48 | + `torch.load` with untrusted data can lead to arbitrary code execution, |
| 49 | + and improper use of `torch.save` might expose sensitive data or lead |
| 50 | + to data corruption. |
| 51 | + """ |
| 52 | + imported = context.is_module_imported_exact("torch") |
| 53 | + qualname = context.call_function_name_qual |
| 54 | + if not imported and isinstance(qualname, str): |
| 55 | + return |
| 56 | + |
| 57 | + qualname_list = qualname.split(".") |
| 58 | + func = qualname_list[-1] |
| 59 | + if all( |
| 60 | + [ |
| 61 | + "torch" in qualname_list, |
| 62 | + func in ["load", "save"], |
| 63 | + not context.check_call_arg_value("map_location", "cpu"), |
| 64 | + ] |
| 65 | + ): |
| 66 | + return bandit.Issue( |
| 67 | + severity=bandit.MEDIUM, |
| 68 | + confidence=bandit.HIGH, |
| 69 | + text="Use of unsafe PyTorch load or save", |
| 70 | + cwe=issue.Cwe.DESERIALIZATION_OF_UNTRUSTED_DATA, |
| 71 | + lineno=context.get_lineno_for_call_arg("load"), |
| 72 | + ) |
0 commit comments