uiXpress
Database Explorer

Security

Comprehensive security implementation details for the Database Explorer feature.

Security Overview

The Database Explorer implements multiple layers of security to protect against common web vulnerabilities and ensure safe database operations.

Authentication & Authorization

User Authentication

  • Requirement: User must be logged into WordPress
  • Capability Check: Requires manage_options capability (administrator only)
  • Verification: Checked on every REST API request
  • Implementation: check_permissions() method in DatabaseExplorer class

Permission Checks

Admin Page Access

if (!current_user_can("manage_options")) {
    return; // Don't add menu item
}

REST API Access

public static function check_permissions($request) {
    if (!current_user_can("manage_options")) {
        return new \WP_Error("rest_forbidden", ...);
    }
    // Nonce verification...
    return true;
}

Password Verification

  • Required For: Table deletion operations
  • Method: WordPress wp_authenticate() function
  • Validation: Verifies password against current user account
  • User Matching: Ensures password matches current logged-in user

CSRF Protection

Nonce Verification

  • Implementation: WordPress nonce system
  • Nonce Name: wp_rest
  • Header: X-WP-Nonce (preferred)
  • Fallback: _wpnonce parameter
  • Verification: wp_verify_nonce() function

Frontend Implementation

  • Nonce Source: Retrieved from script tag data attribute
  • Header Inclusion: Automatically included in all API requests
  • Automatic Handling: Managed by lmnFetch utility function

Input Validation

Table Name Validation

Format Validation

  • Pattern: /^[a-zA-Z0-9_]+$/ (alphanumeric and underscores only)
  • Length Check: 1-64 characters
  • Implementation: validate_table_name() method

Existence Validation

  • Check: Verifies table exists before operations
  • Query: SHOW TABLES LIKE %s
  • Error: Returns 404 if table not found

SQL Query Validation

Query Type Restriction

  • Allowed: SELECT queries only
  • Blocked: DROP, DELETE, UPDATE, INSERT, ALTER, CREATE, TRUNCATE, EXEC, EXECUTE, CALL
  • Check: Performed after comment removal

Comment Removal

  • Single-line: Removes -- comments
  • Multi-line: Removes /* */ comments
  • Purpose: Prevents comment-based bypass attempts

Whitespace Normalization

  • Process: Normalizes whitespace before validation
  • Purpose: Prevents whitespace-based bypass attempts

Multiple Statement Prevention

  • Check: Detects semicolons in query
  • Validation: Ensures no content after semicolon
  • Error: Returns error if multiple statements detected

Parameter Validation

Pagination Parameters

  • Page: Validated with absint(), must be > 0
  • Per Page: Validated with absint(), must be > 0 and <= 500
  • Default: Page 1, Per Page 50

Sort Parameters

  • Orderby: Validated against actual table columns
  • Order: Must be "ASC" or "DESC"
  • Sanitization: sanitize_text_field()

Search Parameters

  • Sanitization: sanitize_text_field()
  • Escape: $wpdb->esc_like() for LIKE queries
  • Usage: Used in prepared statements

SQL Injection Prevention

Prepared Statements

  • Method: $wpdb->prepare()
  • Usage: All user input in SQL queries
  • Parameters: Table names validated before use
  • Search Terms: Properly escaped with esc_like()

Table Name Handling

  • Validation First: Table names validated before use
  • Escape After Validation: esc_sql() used after validation
  • No Direct Interpolation: Never directly interpolated into queries

Column Name Validation

  • Source: Retrieved from DESCRIBE query
  • Validation: Checked against actual table columns
  • Usage: Only validated columns used in queries

Example Safe Query

// Validate table name
$validated = self::validate_table_name($table_name);
if (!$validated) return error;

// Escape after validation
$escaped = esc_sql($table_name);

// Use in query
$query = "SELECT * FROM `{$escaped}`";

XSS Protection

Output Escaping

Backend Escaping

  • Table Names: esc_html() before JSON encoding
  • Error Messages: Generic messages, no sensitive data
  • JSON Encoding: WordPress REST API handles encoding

Frontend Escaping

  • Function: escapeHtml() utility function
  • Method: Uses DOM textContent to escape HTML
  • Usage: All database values before v-html rendering

HTML Rendering

  • Limited Use: Only for formatted NULL values
  • Escaped Content: All actual data properly escaped
  • Safe HTML: Only trusted HTML rendered

Table Deletion Safety

WordPress Core Table Protection

Detection Method

  • Standard Tables: List of WordPress core table names
  • Prefix Detection: Uses $wpdb->prefix dynamically
  • Name Matching: Compares table name (without prefix) to standard list
  • Multisite Support: Recognizes numbered tables

Protected Tables

Core Tables (12):

  • commentmeta, comments, links, options
  • postmeta, posts, terms, termmeta
  • term_relationships, term_taxonomy
  • usermeta, users

Multisite Tables (6, if enabled):

  • blogs, blog_versions, registration_log
  • signups, site, sitemeta

Implementation

private static function is_wordpress_table($table_name) {
    $table_prefix = $wpdb->prefix;
    $standard_tables = self::get_standard_wp_tables();
    
    if (strpos($table_name, $table_prefix) !== 0) {
        return false;
    }
    
    $base_table_name = substr($table_name, strlen($table_prefix));
    
    if (in_array($base_table_name, $standard_tables)) {
        return true;
    }
    
    // Multisite numbered tables...
    return false;
}

System Table Protection

  • Protected Tables: information_schema, mysql, performance_schema, sys
  • Check: Performed before deletion
  • Error: Returns 403 error if system table

Deletion Process Security

  1. Password Verification: Required before deletion
  2. Table Validation: Checks if safe to delete
  3. Existence Check: Verifies table exists
  4. Audit Logging: Logs all deletions
  5. Error Handling: Generic error messages

Information Disclosure Prevention

Error Messages

  • Generic Messages: No detailed SQL errors exposed
  • User-Friendly: Clear, actionable messages
  • No Stack Traces: No technical details in errors
  • Status Codes: Appropriate HTTP status codes

Query Errors

  • Generic Response: "Query execution failed. Please check your SQL syntax."
  • No Details: Doesn't expose database structure
  • No SQL Errors: Doesn't show actual SQL error messages

Audit Logging

Deletion Logging

  • Format: [Database Explorer] User {username} ({id}) deleted table: {table_name}
  • Location: WordPress error log
  • Information: User login, user ID, table name, timestamp
  • Purpose: Accountability and audit trail

Password Field Security

Autofill Prevention

  • Multiple Techniques: Hidden dummy fields, custom name, autocomplete value
  • Focus Handler: Clears autofilled values on focus
  • Custom Name: verify-password instead of password
  • Autocomplete: new-password value

Password Storage

  • No Storage: Password not stored after verification
  • Temporary Use: Only used during deletion request
  • Cleared: Immediately cleared after use

Rate Limiting Considerations

Current Implementation

  • No Rate Limiting: Currently not implemented
  • Recommendation: Consider adding for production
  • Potential Limits: Queries per minute, data retrieval limits

Security Best Practices Followed

  1. Principle of Least Privilege: Only administrators can access
  2. Defense in Depth: Multiple security layers
  3. Input Validation: All inputs validated and sanitized
  4. Output Escaping: All outputs properly escaped
  5. Prepared Statements: SQL injection prevention
  6. CSRF Protection: Nonce verification
  7. Password Verification: Required for destructive operations
  8. Audit Logging: All deletions logged
  9. Error Handling: No information disclosure
  10. Read-Only Queries: Only SELECT queries allowed

Security Audit

A comprehensive security audit was performed on the Database Explorer feature. See the Security Audit Report for detailed findings and fixes.

Audit Results

  • ✅ All critical vulnerabilities fixed
  • ✅ SQL injection prevention implemented
  • ✅ XSS protection in place
  • ✅ Authentication and authorization verified
  • ✅ Input validation comprehensive
  • ✅ Output escaping complete

Recommendations

For Production Use

  1. Rate Limiting: Implement query rate limiting
  2. Query Timeout: Add execution timeout limits
  3. Backup Reminder: Warn users before deletions
  4. Activity Logging: Consider more detailed activity logs
  5. IP Whitelisting: Optional IP-based access control

For Enhanced Security

  1. Two-Factor Authentication: Require 2FA for deletions
  2. Deletion Confirmation: Require typing table name
  3. Soft Delete: Consider renaming instead of deleting
  4. Backup Before Delete: Automatic backup before deletion
  5. Granular Permissions: Separate capability for database access

Compliance

The Database Explorer security implementation follows:

  • OWASP Top 10: Protection against common vulnerabilities
  • WordPress Coding Standards: Follows WordPress security best practices
  • CWE Top 25: Addresses common weakness enumerations
  • PCI DSS: Suitable for environments requiring compliance