December 22, 2024

SQL Injection Attack – Hacker Challenge

SQL Injection

Overview

A SQL injection (SQLi) is a type of cybersecurity attack that targets data-driven applications by inserting or “injecting” malicious SQL statements in the input field of a web page. Structured Query Language (SQL) is is a standardized programming language that is used to communicate with databases. A successful SQLi can allow an attacker to read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database, or even gain root access to the system itself. The SQLi Hacker Challenge is an chance for you to conduct a SQLi attack on a mock database that was designed for this challenge. If successful, you’ll have an opportunity to answer some fun Bonus Questions.

Before we begin, let’s go over an example of SQLi attack.

SQL Injection example

Look at the following example which creates a SELECT statement by adding a variable (user_id) to the end of it. The variable is fetched from the input() function.

user_id = input("User ID: ")
SQL_statement = f"SELECT * FROM Users WHERE user_id = {user_id};"

The purpose of the code is to create a SQL statement to select a user, with a given user_id. If there are no security measures in place then a user can enter erroneous data into the input field such as:

User Id: 76 OR 1=1

This would create the following SQL statement:

SELECT * FROM Users WHERE user_id = 76 OR 1=1;

The above SQL statement is valid and will return ALL rows from the “Users” table, since OR 1=1 is always TRUE. If the “Users” table contains usernames and passwords then a hacker would get access to all the usernames and passwords in a database, by simply inserting OR 1=1 into the input field.

Now that you have a basic understanding of how a SQLi works, lets try the SQLi Hacker Challenge.

SQL Injection Lab

Task

Your task is to execute a successful SQLi attack on a mock database that was designed for this challenge, and to view all contents in.

Database design

The database consists of one table, and the following three columns:

  • id
  • username
  • password

Instructions

Run the following Python script on your local machine, and you will be prompted to “Enter your SQL Injection.” Keep trying until you successfully achieve a SQLi attack!

#!/usr/bin/env python3
import sqlite3
import requests

# SQL statements:
CREATE_USERS_TABLE = "CREATE TABLE IF NOT EXISTS usernames (id INTEGER PRIMARY KEY, username TEXT, password TEXT);"
INSERT_USER_DATA = "INSERT INTO usernames (username, password) VALUES (?, ?)"


def get_userdata() -> list:
    """Returns username, and password in tuple from online username.dat file."""
    # url to username and password file
    URL = "https://pastebin.com/raw/ih7szSSv"
    raw = [i.strip() for i in requests.get(URL).text.split('\n')]
    output = []
    for i in raw:
        users = i.split(', ')[0].split(',')[0]
        passwords = i.split(', ')[0].split(',')[1]
        output.append((users, passwords))
    return output


# Create database in memory
conn = sqlite3.connect(":memory:")
# Get usernames and passwords
user_data = get_userdata()

# Create table
conn.execute(CREATE_USERS_TABLE)
# Insert username, passwords into database
conn.executemany(INSERT_USER_DATA, user_data)


while True:
    INJECTION = input("Enter your SQL Injection:\n>  ")
    sql = f"SELECT * FROM usernames WHERE id = 776 {INJECTION}"
    try:
        results = conn.execute(sql).fetchall()
        if results:
            print(f"\n\033[92m" + "Good job, you did it!" + "\033[0m")
            with conn:
                for row in results:
                    print(row)
            conn.close()
            break
    except sqlite3.OperationalError as e:
        print("\n\033[91m" + "Nope, try again!" + "\033[0m")
        pass

Bonus Questions

After dumping the database, try solving the following Bonus Questions.

  1. Decrypt the administrator’s password. Hint: MD(101)
  2. What 1995 "crime/action/romance" movie did these users play in? Hint: Solve the first bonus question.

Conclusion

The main purpose of this tutorial was to teach basic techniques on how to conduct a SQLi attack. Hopefully you were able to successfully execute a SQLi attack, and solve all of the Bonus Questions. If you want a better SQLi graphic user interface then check out the SQL Injection Lab hosted on Hacksplaining. Please leave your questions, concerns or comments below. Thanks for reading this post ~ Good luck and have fun!


Code available at GitHub

Leave a Reply

Your email address will not be published.