Skip to content

Commit 1173cd3

Browse files
fix: remove unsafe pickle deserialization in txt_to_obj (CVE CWE-502)
Signed-off-by: yashasvi <yashasvi@ibm.com>
1 parent d3c30a0 commit 1173cd3

3 files changed

Lines changed: 14 additions & 13 deletions

File tree

build/utils.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@
1313
# limitations under the License.
1414

1515
# Standard
16-
import os
17-
import logging
18-
import pickle
1916
import base64
17+
import json
18+
import logging
19+
import os
2020

2121
# Third Party
2222
import torch
@@ -67,14 +67,21 @@ def get_highest_checkpoint(dir_path):
6767
return checkpoint_dir
6868

6969

70+
def _json_default(obj):
71+
"""Fallback serializer for objects not natively JSON-serializable."""
72+
if hasattr(obj, "__dict__"):
73+
return obj.__dict__
74+
return str(obj)
75+
76+
7077
def serialize_args(args_json):
7178
"""Given dict, converts to base64 byte representation.
7279
7380
Args:
7481
args_json: dict
7582
Returns: str
7683
"""
77-
message_bytes = pickle.dumps(args_json)
84+
message_bytes = json.dumps(args_json, default=_json_default).encode("utf-8")
7885
base64_bytes = base64.b64encode(message_bytes)
7986
return base64_bytes.decode("ascii")
8087

tests/utils/test_config_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
# Standard
1919
import base64
20-
import pickle
20+
import json
2121

2222
# Third Party
2323
from datasets import Dataset, Features, Value
@@ -224,7 +224,7 @@ def test_get_json_config_can_load_from_envvar(monkeypatch):
224224
the json path from env var SFT_TRAINER_CONFIG_JSON_ENV_VAR
225225
"""
226226
config_json = {"model_name_or_path": "foobar"}
227-
message_bytes = pickle.dumps(config_json)
227+
message_bytes = json.dumps(config_json).encode("utf-8")
228228
base64_bytes = base64.b64encode(message_bytes)
229229
encoded_json = base64_bytes.decode("ascii")
230230
monkeypatch.delenv("SFT_TRAINER_CONFIG_JSON_PATH", raising=False)

tuning/utils/config_utils.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
import base64
1818
import json
1919
import os
20-
import pickle
2120

2221
# Third Party
2322
from peft import PromptTuningConfig as HFPromptTuningConfig
@@ -159,9 +158,4 @@ def txt_to_obj(txt):
159158
"""
160159
base64_bytes = txt.encode("ascii")
161160
message_bytes = base64.b64decode(base64_bytes)
162-
try:
163-
# If the bytes represent JSON string
164-
return json.loads(message_bytes)
165-
except UnicodeDecodeError:
166-
# Otherwise the bytes are a pickled python dictionary
167-
return pickle.loads(message_bytes)
161+
return json.loads(message_bytes)

0 commit comments

Comments
 (0)