Skip to content

Instantly share code, notes, and snippets.

@lynt-smitka
Last active September 1, 2022 20:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lynt-smitka/425e4e97c61cac172e229ffc9ad090e4 to your computer and use it in GitHub Desktop.
Save lynt-smitka/425e4e97c61cac172e229ffc9ad090e4 to your computer and use it in GitHub Desktop.
This MU plugin blocks attempts to install WP to remote databases. https://smitka.me/2022/07/01/wordpress-installer-attack-race/
<?php
/**
* Plugin Name: Lynt WP Installer Security PoC1
* Author: Vladimir Smitka
* Author URI: https://lynt.cz/
* License: GNU General Public License v3 or later
* License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
if ( defined( 'WP_SETUP_CONFIG' ) && !empty( $_POST['dbhost'] ) ) {
$dbhost = trim( wp_unslash( $_POST['dbhost'] ) );
// default settings - allow localhost only
// possible enhacement: translate host to IP and allow local subnets
$allowed_dbhost_regexp = '^(?:localhost|127\.0\.0\.1)$';
// if there is enviroment varianle defined use it
// the webhoster can modify default settings
if ( getenv( 'WP_ALLOWED_DBHOSTS' ) ) {
$allowed_dbhost_regexp = getenv( 'WP_ALLOWED_DBHOSTS' );
}
// the user can change the default behavior via wp-dbhosts.php
// can set his own DB hosts or disable limit by "false"
if ( file_exists( ABSPATH . '/wp-dbhosts.php' ) ) {
require_once ABSPATH . '/wp-dbhosts.php';
if ( defined( 'WP_ALLOWED_DBHOSTS' ) ) {
//if false skip the check later
if ( !WP_ALLOWED_DBHOSTS ) {
$allowed_dbhost_regexp = false;
}
else {
$allowed_dbhost_regexp = WP_ALLOWED_DBHOSTS;
}
}
}
// check if dbhost is allowed
if( $allowed_dbhost_regexp ) {
if ( !preg_match( '#' . $allowed_dbhost_regexp . '#i', $dbhost)) {
wp_die('The selected database server has been blocked.
Allowed servers can be managed using environment
variable or a constant in wp-config.php.');
}
}
}
<?php
// Example of the optional file to define allowed DB hosts
if ( ! defined( 'WP_ALLOWED_DBHOSTS' ) ) {
define( 'WP_ALLOWED_DBHOSTS', '^(?:localhost|127\.0\.0\.1)$');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment