The vulnerability exists in the SQLChatAgent class within the langroid library, specifically in the run_query method. This method is designed to execute SQL queries generated by an LLM. The core of the vulnerability lies in the trust placed in the LLM's output. The agent would execute any SQL query provided by the model without verification. An attacker could exploit this by using prompt injection to manipulate the LLM into generating malicious SQL statements. The provided proof-of-concept demonstrates this by base64-encoding a malicious SQL payload, which the LLM is instructed to decode and execute. This payload uses a PostgreSQL-specific command (COPY ... FROM PROGRAM) to achieve remote code execution on the database host.
The fixing commit (60933b4860a8952894b31caa0dd3f9dcba512c8e) addresses this by introducing a validation layer. A new method, _validate_query, is added, which is called at the start of run_query. This new method uses the sqlglot library to parse the incoming SQL query and checks it against a configurable allowlist of statement types (defaulting to ["SELECT"]) and a blocklist of known dangerous SQL patterns. By default, any query that is not a SELECT statement or contains dangerous constructs is rejected, thus preventing the SQL injection and subsequent RCE. The vulnerable function is SQLChatAgent.run_query as it was the entry point for executing the unsanitized, user-influenced SQL query.