fix(security): dynamic module loading uses unsanitized class name

Multiple factory helpers build import paths from `class_name` and only gate with `os.path.exists(...)`. If `class_name` can be influenced by configuration or user-controlled input, an attacker may load unintended modules or traverse paths, resulting in arbitrary code execution through import side effects.

Affected files: llm.py

Signed-off-by: tuanaiseo <221258316+tuanaiseo@users.noreply.github.com>
This commit is contained in:
tuanaiseo 2026-04-08 06:32:40 +07:00
parent c5f82369e5
commit d77f12db31

View file

@ -8,16 +8,42 @@ sys.path.insert(0, project_root)
from config.logger import setup_logging from config.logger import setup_logging
import importlib import importlib
import re
logger = setup_logging() logger = setup_logging()
_VALID_CLASS_NAME = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')
def _build_llm_module_map():
module_map = {}
base_dir = os.path.join(project_root, 'core', 'providers', 'llm')
if not os.path.isdir(base_dir):
return module_map
for name in os.listdir(base_dir):
if not _VALID_CLASS_NAME.fullmatch(name):
continue
provider_file = os.path.join(base_dir, name, f'{name}.py')
if os.path.isfile(provider_file):
module_map[name] = f'core.providers.llm.{name}.{name}'
return module_map
LLM_MODULE_MAP = _build_llm_module_map()
def create_instance(class_name, *args, **kwargs): def create_instance(class_name, *args, **kwargs):
# 创建LLM实例 # 创建LLM实例
if os.path.exists(os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py')): if not isinstance(class_name, str) or not _VALID_CLASS_NAME.fullmatch(class_name):
lib_name = f'core.providers.llm.{class_name}.{class_name}' raise ValueError(f"不支持的LLM类型: {class_name},请检查该配置的type是否设置正确")
lib_name = LLM_MODULE_MAP.get(class_name)
if lib_name:
if lib_name not in sys.modules: if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f'{lib_name}') sys.modules[lib_name] = importlib.import_module(lib_name)
return sys.modules[lib_name].LLMProvider(*args, **kwargs) return sys.modules[lib_name].LLMProvider(*args, **kwargs)
raise ValueError(f"不支持的LLM类型: {class_name},请检查该配置的type是否设置正确") raise ValueError(f"不支持的LLM类型: {class_name},请检查该配置的type是否设置正确")