DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for SQL Injection Hacker Challenge
Seraphβ˜…776
Seraphβ˜…776

Posted on

SQL Injection Hacker Challenge

πŸ’‘ 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. 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 another opportunity to answer some fun Bonus Questions.

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

SQLi 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};"
Enter fullscreen mode Exit fullscreen mode

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: 776 OR 1=1
Enter fullscreen mode Exit fullscreen mode

This would create the following SQL statement:

SELECT * FROM Users WHERE user_id = 776 OR 1=1;
Enter fullscreen mode Exit fullscreen mode

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 776 OR 1=1 into the input field.

SQLi Hacker Challenge

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

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 entering input 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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.