MySQL Triggers for WordPress Database Audit Logging

MySQL triggers as an audit log for WordPress options

Some changes in a WordPress database come from nowhere: the admin email is suddenly different, users_can_register is on, a plugin appears in active_plugins. A logging plugin records what happens through WordPress, but not what a script, a database tool or an attacker with database access changes directly. A trigger in MySQL sees every change to a table, whatever its source.

Problem: On a client site, admin_email and default_role were changed and nobody knows when or how. The activity log plugin has no entry, so the change did not go through WordPress functions.

Solution: Create an audit table and an AFTER UPDATE trigger on wp_options that writes the old and the new value of a list of sensitive options together with the time and the database user and connection, plus an AFTER INSERT trigger for new administrator capabilities in wp_usermeta.

The audit table

CREATE TABLE wp_ha_audit (
    id          BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    changed_at  DATETIME(3)     NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    db_user     VARCHAR(128)    NOT NULL,
    conn_id     BIGINT UNSIGNED NOT NULL,
    table_name  VARCHAR(64)     NOT NULL,
    row_key     VARCHAR(191)    NOT NULL,
    old_value   MEDIUMTEXT,
    new_value   MEDIUMTEXT,
    PRIMARY KEY (id),
    KEY changed_at (changed_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

The trigger on wp_options

DROP TRIGGER IF EXISTS wp_ha_options_audit;

DELIMITER $$
CREATE TRIGGER wp_ha_options_audit
AFTER UPDATE ON wp_options
FOR EACH ROW
BEGIN
    IF NEW.option_name IN ('admin_email', 'siteurl', 'home', 'default_role',
                           'users_can_register', 'active_plugins', 'template', 'stylesheet')
       AND NOT (OLD.option_value <=> NEW.option_value) THEN
        INSERT INTO wp_ha_audit (db_user, conn_id, table_name, row_key, old_value, new_value)
        VALUES (CURRENT_USER(), CONNECTION_ID(), 'wp_options', NEW.option_name,
                OLD.option_value, NEW.option_value);
    END IF;
END$$
DELIMITER ;

<=> is the NULL-safe comparison: with !=, a change from or to NULL would not be logged. The trigger runs inside the same transaction as the update; if the insert into the audit table fails, the update of the option fails too, so the audit table must exist before the trigger is created.

DELIMITER is a command of the mysql client, not SQL: it allows the semicolons inside the trigger body. In phpMyAdmin, paste the statement without the DELIMITER lines and set the delimiter field under the SQL box to $$.

New administrators in wp_usermeta

DROP TRIGGER IF EXISTS wp_ha_caps_audit;

DELIMITER $$
CREATE TRIGGER wp_ha_caps_audit
AFTER INSERT ON wp_usermeta
FOR EACH ROW
BEGIN
    IF NEW.meta_key = 'wp_capabilities' AND NEW.meta_value LIKE '%administrator%' THEN
        INSERT INTO wp_ha_audit (db_user, conn_id, table_name, row_key, new_value)
        VALUES (CURRENT_USER(), CONNECTION_ID(), 'wp_usermeta', CONCAT('user ', NEW.user_id), NEW.meta_value);
    END IF;
END$$
DELIMITER ;

A second trigger AFTER UPDATE ON wp_usermeta with the same condition catches existing users who are promoted. The meta key contains the table prefix: wp_capabilities for the prefix wp_.

Read the log

SELECT changed_at, db_user, conn_id, row_key, LEFT(old_value, 80) AS old_v, LEFT(new_value, 80) AS new_v
FROM wp_ha_audit
ORDER BY id DESC
LIMIT 50;

CURRENT_USER() is the MySQL account. WordPress always connects with the account from wp-config.php, so all changes made through WordPress show the same user; a different account in the log (a backup tool, a developer’s login, a stolen database password) is exactly the case the log is for. The connection ID helps to match entries with the general or slow query log of that time. Which WordPress user made a change is not visible to MySQL; that part stays the job of a logging plugin: log WordPress user activity.

Permissions and limits

Creating a trigger needs the TRIGGER privilege. With binary logging enabled (replication, point-in-time backups), MySQL also requires SUPER or log_bin_trust_function_creators = 1, which many managed hosts do not grant. Triggers are part of the table: mysqldump exports them by default, and some migration tools do not, so after a move, check with SHOW TRIGGERS LIKE 'wp_options';.

NOTE: Keep the list of options short. wp_options is updated on almost every request (transients, cron, sessions), and a trigger that logs every row would make each of those writes slower and fill the table in days. Old entries can be removed with a scheduled DELETE ... WHERE changed_at < NOW() - INTERVAL 90 DAY. Other database objects with WordPress tables: MySQL stored procedures.